260706_1_계정, 로그인, 보안 초안 작성

This commit is contained in:
2026-07-07 19:17:13 +09:00
parent 404941c47a
commit f8633bb1fe
4696 changed files with 6110 additions and 642171 deletions
+30 -291
View File
@@ -1,38 +1,16 @@
{
"name": "forest-road-design",
"name": "forest-road-webapp",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"frontend": {
"name": "forest-road-frontend",
"dependencies": {
"geotiff": "^3.0.5",
"lucide-react": "^1.23.0",
"maplibre-gl": "^5.24.0",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"three": "^0.185.0"
},
"devDependencies": {
"@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3",
"@types/three": "^0.185.0",
"@vitejs/plugin-react": "^6.0.3",
"typescript": "^6.0.3",
"vite": "^8.1.0"
}
},
"node_modules/@dimforge/rapier3d-compat": {
"version": "0.12.0",
"resolved": "https://registry.npmjs.org/@dimforge/rapier3d-compat/-/rapier3d-compat-0.12.0.tgz",
"integrity": "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow==",
"dev": true,
"license": "Apache-2.0"
},
"node_modules/@mapbox/jsonlint-lines-primitives": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/@mapbox/jsonlint-lines-primitives/-/jsonlint-lines-primitives-2.0.3.tgz",
"integrity": "sha512-0SElaV0uMxEnxzBhhX9WTuPyUeMsAN/SS0i16tjuba4/mio63MG9khjC1a0JAiPGXAwvwm4UfHJURCN7nyudQg==",
"license": "MIT",
"engines": {
"node": ">= 22"
@@ -40,26 +18,18 @@
},
"node_modules/@mapbox/point-geometry": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@mapbox/point-geometry/-/point-geometry-1.1.0.tgz",
"integrity": "sha512-YGcBz1cg4ATXDCM/71L9xveh4dynfGmcLDqufR+nQQy3fKwsAZsWd/x4621/6uJaeB9mwOHE6hPeDgXz9uViUQ==",
"license": "ISC"
},
"node_modules/@mapbox/tiny-sdf": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/@mapbox/tiny-sdf/-/tiny-sdf-2.2.0.tgz",
"integrity": "sha512-LVL4wgI9YAum5V+LNVQO6QgFBPw7/MIIY4XJPNsPDMrjEwcE+JfKk1LuIl8GnF197ejVdC9QdPaxrx5gfgdGXg==",
"license": "BSD-2-Clause"
},
"node_modules/@mapbox/unitbezier": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/@mapbox/unitbezier/-/unitbezier-0.0.1.tgz",
"integrity": "sha512-nMkuDXFv60aBr9soUG5q+GvZYL+2KZHVvsqFCzqnkGEf46U2fvmytHaEVc1/YZbiLn8X+eR3QzX1+dwDO1lxlw==",
"license": "BSD-2-Clause"
},
"node_modules/@mapbox/vector-tile": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/@mapbox/vector-tile/-/vector-tile-2.0.5.tgz",
"integrity": "sha512-pXj8m7KTsqZt+1jsE0xIpGvqTSbblfkuEJL/NJmNePMtEwxO8V3XMDo9WMSfDeqHvCtBI9Lmt4mGcGR10zecmw==",
"license": "BSD-3-Clause",
"dependencies": {
"@mapbox/point-geometry": "~1.1.0",
@@ -69,8 +39,6 @@
},
"node_modules/@mapbox/whoots-js": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/@mapbox/whoots-js/-/whoots-js-3.1.0.tgz",
"integrity": "sha512-Es6WcD0nO5l+2BOQS4uLfNPYQaNDfbot3X1XUoloz+x0mPDS3eeORZJl06HXjwBG1fOGwCRnzK88LMdxKRrd6Q==",
"license": "ISC",
"engines": {
"node": ">=6.0.0"
@@ -78,8 +46,6 @@
},
"node_modules/@maplibre/geojson-vt": {
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/@maplibre/geojson-vt/-/geojson-vt-6.1.0.tgz",
"integrity": "sha512-2eIY4gZxeKIVOZVNkAMb+5NgXhgsMQpOveTQAvnp53LYqHGJZDidk7Ew0Tged9PThidpbS+NFTh0g4zivhPDzQ==",
"license": "ISC",
"dependencies": {
"kdbush": "^4.0.2"
@@ -87,8 +53,6 @@
},
"node_modules/@maplibre/maplibre-gl-style-spec": {
"version": "24.10.0",
"resolved": "https://registry.npmjs.org/@maplibre/maplibre-gl-style-spec/-/maplibre-gl-style-spec-24.10.0.tgz",
"integrity": "sha512-lichxSiagMEBBrqHF0trtMQH9RKh+9jUlIJl0qW0QHvt2H/tbvUWdE+ZzI2Jd0/pT7j/iavLonlPu7EQ/ixTOw==",
"license": "ISC",
"dependencies": {
"@mapbox/jsonlint-lines-primitives": "~2.0.2",
@@ -106,14 +70,10 @@
},
"node_modules/@maplibre/maplibre-gl-style-spec/node_modules/@mapbox/unitbezier": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@mapbox/unitbezier/-/unitbezier-1.0.0.tgz",
"integrity": "sha512-fqd515fjBmANKGGsQ286E2Wvj/XvDFpGzwJxq4CI6jMQue6Oy04uCKp+JWKF00xRTmk6cEu1jPJ9p3xqH8YWqQ==",
"license": "BSD-2-Clause"
},
"node_modules/@maplibre/mlt": {
"version": "1.1.12",
"resolved": "https://registry.npmjs.org/@maplibre/mlt/-/mlt-1.1.12.tgz",
"integrity": "sha512-ZeK5w2TTeHOajcLaEQs1KZXw2V9wIKo1PmThlxlsHoXsQsYlBqLJzPOd6tJHRtGTChUY3DPPmjXRArYVvAbmZw==",
"license": "(MIT OR Apache-2.0)",
"dependencies": {
"@mapbox/point-geometry": "^1.1.0"
@@ -121,8 +81,6 @@
},
"node_modules/@maplibre/vt-pbf": {
"version": "4.3.2",
"resolved": "https://registry.npmjs.org/@maplibre/vt-pbf/-/vt-pbf-4.3.2.tgz",
"integrity": "sha512-j6p0AdjvAR19Z3XaCysle7A4ZSo08tYOzxD0Y9NQylwPAkwJJeYub5b2eVucdeDh7erhv69DahoLOevDRERRUw==",
"license": "MIT",
"dependencies": {
"@mapbox/point-geometry": "^1.1.0",
@@ -132,8 +90,6 @@
},
"node_modules/@maplibre/vt-pbf/node_modules/pbf": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/pbf/-/pbf-5.1.0.tgz",
"integrity": "sha512-Wv0yo0+uZepnoNEKsquhar1F18LogB8oeEikIhUXG16udbiXG7JecHGySwoo6kuMgjmbQYzdrTZlO+/K9t8eZg==",
"license": "BSD-3-Clause",
"dependencies": {
"resolve-protobuf-schema": "^2.1.0"
@@ -144,24 +100,14 @@
},
"node_modules/@oxc-project/types": {
"version": "0.137.0",
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.137.0.tgz",
"integrity": "sha512-WT+Gb24i8hmvo85AIv2oEYouEXkRlKAlT9WaCa3TfLgNCN+GhrJOGZuIlMouAh38Qe4QOx26eUOVsq70qXrywA==",
"dev": true,
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/Boshen"
}
},
"node_modules/@petamoriken/float16": {
"version": "3.9.3",
"resolved": "https://registry.npmjs.org/@petamoriken/float16/-/float16-3.9.3.tgz",
"integrity": "sha512-8awtpHXCx/bNpFt4mt2xdkgtgVvKqty8VbjHI/WWWQuEw+KLzFot3f4+LkQY9YmOtq7A5GdOnqoIC8Pdygjk2g==",
"license": "MIT"
},
"node_modules/@rolldown/binding-win32-x64-msvc": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.1.3.tgz",
"integrity": "sha512-OL4OMk7UPXOeVGGd3qo5zJyPIljf4AFgk5QAkPPS+OoLuOOozhuaQGC18MxVTnw/06q93gShAJzlwnSCY9YtqA==",
"cpu": [
"x64"
],
@@ -177,55 +123,35 @@
},
"node_modules/@rolldown/pluginutils": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz",
"integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==",
"dev": true,
"license": "MIT"
},
"node_modules/@tweenjs/tween.js": {
"version": "23.1.3",
"resolved": "https://registry.npmjs.org/@tweenjs/tween.js/-/tween.js-23.1.3.tgz",
"integrity": "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/geojson": {
"version": "7946.0.16",
"resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz",
"integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==",
"license": "MIT"
},
"node_modules/@types/react": {
"version": "19.2.17",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.17.tgz",
"integrity": "sha512-MXfmqaVPEVgkBT/aY0aGCkRWWtByiYQXo3xdQ8r5RzuFrPiRn8Gar2tQdXSUQ2GKV3bkXckek89V8wQBY2Q/Aw==",
"node_modules/@types/node": {
"version": "26.1.0",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.1.0.tgz",
"integrity": "sha512-O0A1G3xPGy4w7AgQdAQYUlQ+BKk2Oovw8eRpofyp5KdBZULnbe+WqaOVNrm705SHphCiG4XHsACrSmPu1f+Kgw==",
"dev": true,
"license": "MIT",
"dependencies": {
"csstype": "^3.2.2"
}
},
"node_modules/@types/react-dom": {
"version": "19.2.3",
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.3.tgz",
"integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==",
"dev": true,
"license": "MIT",
"peerDependencies": {
"@types/react": "^19.2.0"
"undici-types": "~8.3.0"
}
},
"node_modules/@types/stats.js": {
"version": "0.17.4",
"resolved": "https://registry.npmjs.org/@types/stats.js/-/stats.js-0.17.4.tgz",
"integrity": "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/three": {
"version": "0.185.0",
"resolved": "https://registry.npmjs.org/@types/three/-/three-0.185.0.tgz",
"integrity": "sha512-O2Uy8Cj4Nonr8dWUUbifMdPe8B0Mq7EdOHb89S4+kjUw/KhbjTZrUuYlrQ1bpUKG+EP9QJnN7qNxbHGlGoLHMA==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -239,48 +165,11 @@
},
"node_modules/@types/webxr": {
"version": "0.5.24",
"resolved": "https://registry.npmjs.org/@types/webxr/-/webxr-0.5.24.tgz",
"integrity": "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==",
"dev": true,
"license": "MIT"
},
"node_modules/@vitejs/plugin-react": {
"version": "6.0.3",
"resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.0.3.tgz",
"integrity": "sha512-vmFvco5/QuC2f9Oj+wTk0+9XeDFkHxSamwZKYc7MxYwKICfvUvlMhqKI0VuICPltGqh1neqBKDvO4kes1ya8vg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@rolldown/pluginutils": "^1.0.1"
},
"engines": {
"node": "^20.19.0 || >=22.12.0"
},
"peerDependencies": {
"@rolldown/plugin-babel": "^0.1.7 || ^0.2.0",
"babel-plugin-react-compiler": "^1.0.0",
"vite": "^8.0.0"
},
"peerDependenciesMeta": {
"@rolldown/plugin-babel": {
"optional": true
},
"babel-plugin-react-compiler": {
"optional": true
}
}
},
"node_modules/csstype": {
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
"dev": true,
"license": "MIT"
},
"node_modules/detect-libc": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
"integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
"dev": true,
"license": "Apache-2.0",
"engines": {
@@ -289,14 +178,10 @@
},
"node_modules/earcut": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/earcut/-/earcut-3.0.2.tgz",
"integrity": "sha512-X7hshQbLyMJ/3RPhyObLARM2sNxxmRALLKx1+NVFFnQ9gKzmCrxm9+uLIAdBcvc8FNLpctqlQ2V6AE92Ol9UDQ==",
"license": "ISC"
},
"node_modules/fdir": {
"version": "6.5.0",
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
"integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
"dev": true,
"license": "MIT",
"engines": {
@@ -313,62 +198,23 @@
},
"node_modules/fflate": {
"version": "0.8.3",
"resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz",
"integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==",
"dev": true,
"license": "MIT"
},
"node_modules/forest-road-frontend": {
"resolved": "frontend",
"link": true
},
"node_modules/geotiff": {
"version": "3.0.5",
"resolved": "https://registry.npmjs.org/geotiff/-/geotiff-3.0.5.tgz",
"integrity": "sha512-OWcL9S9+yDZ6iAlXMt32T1iwUApJM8UiD47xbm6ZP1h33d10fqkPs14EG/ttT5EnefpZSx3G15iDFC5FxUNUwA==",
"license": "MIT",
"dependencies": {
"@petamoriken/float16": "^3.9.3",
"lerc": "^3.0.0",
"pako": "^2.0.4",
"parse-headers": "^2.0.2",
"quick-lru": "^6.1.1",
"web-worker": "^1.5.0",
"xml-utils": "^1.10.2",
"zstddec": "^0.2.0"
},
"engines": {
"node": ">=10.19"
}
},
"node_modules/gl-matrix": {
"version": "3.4.4",
"resolved": "https://registry.npmjs.org/gl-matrix/-/gl-matrix-3.4.4.tgz",
"integrity": "sha512-latSnyDNt/8zYUB6VIJ6PCh2jBjJX6gnDsoCZ7LyW7GkqrD51EWwa9qCoGixj8YqBtETQK/xY7OmpTF8xz1DdQ==",
"license": "MIT"
},
"node_modules/json-stringify-pretty-compact": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/json-stringify-pretty-compact/-/json-stringify-pretty-compact-4.0.0.tgz",
"integrity": "sha512-3CNZ2DnrpByG9Nqj6Xo8vqbjT4F6N+tb4Gb28ESAZjYZ5yqvmc56J+/kuIwkaAMOyblTQhUW7PxMkUb8Q36N3Q==",
"license": "MIT"
},
"node_modules/kdbush": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/kdbush/-/kdbush-4.1.0.tgz",
"integrity": "sha512-e9vurzrXJQrFX6ckpHP3bvj5l+9CnYzkxDNnNQ1h2QTqdWsUAJgXiKdGNcOa1EY85dU8KbQ+z/FdQdB7P+9yfQ==",
"license": "ISC"
},
"node_modules/lerc": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/lerc/-/lerc-3.0.0.tgz",
"integrity": "sha512-Rm4J/WaHhRa93nCN2mwWDZFoRVF18G1f47C+kvQWyHGEZxFpTUi73p7lMVSAndyxGt6lJ2/CFbOcf9ra5p8aww==",
"license": "Apache-2.0"
},
"node_modules/lightningcss": {
"version": "1.32.0",
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz",
"integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==",
"dev": true,
"license": "MPL-2.0",
"dependencies": {
@@ -397,8 +243,6 @@
},
"node_modules/lightningcss-win32-x64-msvc": {
"version": "1.32.0",
"resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.32.0.tgz",
"integrity": "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==",
"cpu": [
"x64"
],
@@ -416,19 +260,8 @@
"url": "https://opencollective.com/parcel"
}
},
"node_modules/lucide-react": {
"version": "1.23.0",
"resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.23.0.tgz",
"integrity": "sha512-38BpJcD0JhFosxHApP/BYsBetLpQFRoTRzEzstM/XCc3jsAG7wqaY1lgVwxiUe3xqYE+lNxo2PkCmYwXWrwwIw==",
"license": "ISC",
"peerDependencies": {
"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/maplibre-gl": {
"version": "5.24.0",
"resolved": "https://registry.npmjs.org/maplibre-gl/-/maplibre-gl-5.24.0.tgz",
"integrity": "sha512-ALyFxgtd5R+65UqZ/++lOqwWcC0SNho9c27fYSyLmG7AfnAul2o46F05aDJGPbFU57wos9dgcIySHs0Xe6ia3A==",
"license": "BSD-3-Clause",
"dependencies": {
"@mapbox/jsonlint-lines-primitives": "^2.0.2",
@@ -461,15 +294,11 @@
},
"node_modules/meshoptimizer": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-1.1.1.tgz",
"integrity": "sha512-oRFNWJRDA/WTrVj7NWvqa5HqE1t9MYDj2VaWirQCzCCrAd2GHrqR/sQezCxiWATPNlKTcRaPRHPJwIRoPBAp5g==",
"dev": true,
"license": "MIT"
},
"node_modules/minimist": {
"version": "1.2.8",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
"integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/ljharb"
@@ -477,14 +306,10 @@
},
"node_modules/murmurhash-js": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/murmurhash-js/-/murmurhash-js-1.0.0.tgz",
"integrity": "sha512-TvmkNhkv8yct0SVBSy+o8wYzXjE4Zz3PCesbfs8HiCXXdcTuocApFv11UWlNFWKYsP2okqrhb7JNlSm9InBhIw==",
"license": "MIT"
},
"node_modules/nanoid": {
"version": "3.3.15",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.15.tgz",
"integrity": "sha512-y7Wygv/7mEOvxTuEQDB8StXdMRBWf1kR/tlhAzBRUFkB2jfcLOAxO/SHmOO2zgz1pVgK29/kyupn059/bCHdjA==",
"dev": true,
"funding": [
{
@@ -500,32 +325,8 @@
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
}
},
"node_modules/pako": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/pako/-/pako-2.2.0.tgz",
"integrity": "sha512-zJq6RP/5q+TO2OpFV3FHzlPnFjmkb7Nc99a5SNjJE+uu/PkpChs+NIZSSzbBoD+6kjiISXjfYdwj1ZRQ81dz/w==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/puzrin"
},
{
"type": "github",
"url": "https://github.com/sponsors/nodeca"
}
],
"license": "(MIT AND Zlib)"
},
"node_modules/parse-headers": {
"version": "2.0.6",
"resolved": "https://registry.npmjs.org/parse-headers/-/parse-headers-2.0.6.tgz",
"integrity": "sha512-Tz11t3uKztEW5FEVZnj1ox8GKblWn+PvHY9TmJV5Mll2uHEwRdR/5Li1OlXoECjLYkApdhWy44ocONwXLiKO5A==",
"license": "MIT"
},
"node_modules/pbf": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/pbf/-/pbf-4.0.2.tgz",
"integrity": "sha512-J0ajxARhZfpUEebxYs1vhMGMuLSXtBe1e+fFPDrf2uA2hgo+UshKfNUWOz92HJNz6/NFEXseQPddnHkTreWRqg==",
"license": "BSD-3-Clause",
"dependencies": {
"resolve-protobuf-schema": "^2.1.0"
@@ -536,15 +337,11 @@
},
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
"integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
"dev": true,
"license": "ISC"
},
"node_modules/picomatch": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
"dev": true,
"license": "MIT",
"engines": {
@@ -556,8 +353,6 @@
},
"node_modules/postcss": {
"version": "8.5.15",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.15.tgz",
"integrity": "sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==",
"dev": true,
"funding": [
{
@@ -585,59 +380,34 @@
},
"node_modules/potpack": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/potpack/-/potpack-2.1.0.tgz",
"integrity": "sha512-pcaShQc1Shq0y+E7GqJqvZj8DTthWV1KeHGdi0Z6IAin2Oi3JnLCOfwnCo84qc+HAp52wT9nK9H7FAJp5a44GQ==",
"license": "ISC"
},
"node_modules/prettier": {
"version": "3.9.4",
"resolved": "https://registry.npmjs.org/prettier/-/prettier-3.9.4.tgz",
"integrity": "sha512-yWG/o/4oJfo036EKAfK6ACAoDOfHeRHx4tuxkfBZiauURiaSmYwlpOr5LQqKtIkRD2z1PLteme2WoxEnj4tHTg==",
"dev": true,
"license": "MIT",
"bin": {
"prettier": "bin/prettier.cjs"
},
"engines": {
"node": ">=14"
},
"funding": {
"url": "https://github.com/prettier/prettier?sponsor=1"
}
},
"node_modules/protocol-buffers-schema": {
"version": "3.6.1",
"resolved": "https://registry.npmjs.org/protocol-buffers-schema/-/protocol-buffers-schema-3.6.1.tgz",
"integrity": "sha512-VG2K63Igkiv9p76tk1lilczEK1cT+kCjKtkdhw1dQZV3k3IXJbd3o6Ho8b9zJZaHSnT2hKe4I+ObmX9w6m5SmQ==",
"license": "MIT"
},
"node_modules/quick-lru": {
"version": "6.1.2",
"resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-6.1.2.tgz",
"integrity": "sha512-AAFUA5O1d83pIHEhJwWCq/RQcRukCkn/NSm2QsTEMle5f2hP0ChI2+3Xb051PZCkLryI/Ir1MVKviT2FIloaTQ==",
"license": "MIT",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/quickselect": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/quickselect/-/quickselect-3.0.0.tgz",
"integrity": "sha512-XdjUArbK4Bm5fLLvlm5KpTFOiOThgfWWI4axAZDWg4E/0mKdZyI9tNEfds27qCi1ze/vwTR16kvmmGhRra3c2g==",
"license": "ISC"
},
"node_modules/react": {
"version": "19.2.7",
"resolved": "https://registry.npmjs.org/react/-/react-19.2.7.tgz",
"integrity": "sha512-HNe9WslTbXmFK8o8cmwgAeJFSBvt1bPdHCVKtaaV+WlAN36mpT4hcRpwbf3fY56ar2oIXzsBpOAiIRHAdY0OlQ==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/react-dom": {
"version": "19.2.7",
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.7.tgz",
"integrity": "sha512-t0BRVXvbiE/o20Hfw669rLbMCDWtYZLvmJigy2f0MxsXF+71pxhR3xOkspmsO8h3ZlNzyibAmtCa3l4lYKk6gQ==",
"license": "MIT",
"dependencies": {
"scheduler": "^0.27.0"
},
"peerDependencies": {
"react": "^19.2.7"
}
},
"node_modules/resolve-protobuf-schema": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/resolve-protobuf-schema/-/resolve-protobuf-schema-2.1.0.tgz",
"integrity": "sha512-kI5ffTiZWmJaS/huM8wZfEMer1eRd7oJQhDuxeCLe3t7N7mX3z94CN0xPxBQxFYQTSNz9T0i+v6inKqSdK8xrQ==",
"license": "MIT",
"dependencies": {
"protocol-buffers-schema": "^3.3.1"
@@ -645,8 +415,6 @@
},
"node_modules/rolldown": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.1.3.tgz",
"integrity": "sha512-1F1eEtUBtFvcGm1HQ9TiUIUHPQG7mSAODrhIzjxoUEFuo8OcbrGLiVLkevNgj84TE4lnHvnumwFjhJO5Eu135g==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -677,16 +445,8 @@
"@rolldown/binding-win32-x64-msvc": "1.1.3"
}
},
"node_modules/scheduler": {
"version": "0.27.0",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",
"integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==",
"license": "MIT"
},
"node_modules/source-map-js": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
"integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
"dev": true,
"license": "BSD-3-Clause",
"engines": {
@@ -695,14 +455,10 @@
},
"node_modules/three": {
"version": "0.185.0",
"resolved": "https://registry.npmjs.org/three/-/three-0.185.0.tgz",
"integrity": "sha512-+yRrcRO2iZa8uzvNNl0d7cL4huhgKgBvVJ0njcTe8xFqZ6DMAFZdCKDP91SEAuj25bNAj7k1QQdf+srZywVK6w==",
"license": "MIT"
},
"node_modules/tinyglobby": {
"version": "0.2.17",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
"integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -718,14 +474,10 @@
},
"node_modules/tinyqueue": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/tinyqueue/-/tinyqueue-3.0.0.tgz",
"integrity": "sha512-gRa9gwYU3ECmQYv3lslts5hxuIa90veaEcxDYuu3QGOIAEM2mOZkVHp48ANJuu1CURtRdHKUBY5Lm1tHV+sD4g==",
"license": "ISC"
},
"node_modules/typescript": {
"version": "6.0.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz",
"integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==",
"dev": true,
"license": "Apache-2.0",
"bin": {
@@ -736,10 +488,15 @@
"node": ">=14.17"
}
},
"node_modules/undici-types": {
"version": "8.3.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz",
"integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==",
"dev": true,
"license": "MIT"
},
"node_modules/vite": {
"version": "8.1.0",
"resolved": "https://registry.npmjs.org/vite/-/vite-8.1.0.tgz",
"integrity": "sha512-BuJcQK/56NQTWDGn4ABea3q4SSBdNPWwNZKTkkUpcMPnLoquSYH8llRtSUIgoL1KSCpHt5eghLShn50mH36y7Q==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -813,24 +570,6 @@
"optional": true
}
}
},
"node_modules/web-worker": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/web-worker/-/web-worker-1.5.0.tgz",
"integrity": "sha512-RiMReJrTAiA+mBjGONMnjVDP2u3p9R1vkcGz6gDIrOMT3oGuYwX2WRMYI9ipkphSuE5XKEhydbhNEJh4NY9mlw==",
"license": "Apache-2.0"
},
"node_modules/xml-utils": {
"version": "1.10.2",
"resolved": "https://registry.npmjs.org/xml-utils/-/xml-utils-1.10.2.tgz",
"integrity": "sha512-RqM+2o1RYs6T8+3DzDSoTRAUfrvaejbVHcp3+thnAtDKo8LskR+HomLajEy5UjTz24rpka7AxVBRR3g2wTUkJA==",
"license": "CC0-1.0"
},
"node_modules/zstddec": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/zstddec/-/zstddec-0.2.0.tgz",
"integrity": "sha512-oyPnDa1X5c13+Y7mA/FDMNJrn4S8UNBe0KCqtDmor40Re7ALrPN6npFwyYVRRh+PqozZQdeg23QtbcamZnG5rA==",
"license": "MIT AND BSD-3-Clause"
}
}
}
-21
View File
@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2017-2025 Kenta Moriuchi
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-413
View File
@@ -1,413 +0,0 @@
# <a href="https://github.com/petamoriken/float16">float16</a>
<p align="center">
IEEE 754 half-precision floating-point ponyfill for JavaScript<br>
See <a href="https://github.com/tc39/proposal-float16array">TC39 proposal</a> or <a href="https://esdiscuss.org/topic/float16array">the archive of the ES Discuss Float16Array topic</a> for details
</p>
<p align="center">
<a href="https://www.npmjs.com/package/@petamoriken/float16"><img src="https://img.shields.io/npm/dw/@petamoriken/float16?logo=npm&amp;style=flat-square" alt="npm downloads"></a>
<a href="https://www.npmjs.com/package/@petamoriken/float16"><img src="https://img.shields.io/npm/v/@petamoriken/float16.svg?label=version&amp;logo=npm&amp;style=flat-square" alt="npm version"></a>
<a href="https://jsr.io/@petamoriken/float16"><img src="https://jsr.io/badges/@petamoriken/float16?label=version&amp;style=flat-square" alt="jsr version"></a>
<br>
<a href="https://github.com/petamoriken/float16/blob/master/package.json"><img src="https://img.shields.io/badge/dependencies-none-brightgreen?style=flat-square" alt="dependencies"></a>
<a href="https://github.com/petamoriken/float16/blob/master/LICENSE"><img src="https://img.shields.io/npm/l/@petamoriken/float16.svg?style=flat-square" alt="license"></a>
<a href="https://codecov.io/gh/petamoriken/float16"><img src="https://img.shields.io/codecov/c/gh/petamoriken/float16?logo=codecov&amp;style=flat-square" alt="codecov"></a>
</p>
<p align="center">
<a href="https://saucelabs.com/u/petamoriken">
<img src="https://app.saucelabs.com/browser-matrix/petamoriken.svg" alt="Sauce Labs browser matrix">
</a>
</p>
## Install
### Node.js
```console
npm install @petamoriken/float16
```
### Deno
> [!NOTE]
> Native float16 features are supported since
> [Deno v1.43](https://deno.com/blog/v1.43#v8-124).
```console
deno add jsr:@petamoriken/float16
```
### Bun
> [!NOTE]
> Native float16 features are supported since
> [Bun v1.1.23](https://bun.sh/blog/bun-v1.1.23#float16array).
```console
bun add @petamoriken/float16
```
## Import
### Node.js, Deno, Bun or Bundler
```js
import {
Float16Array, isFloat16Array, isTypedArray,
getFloat16, setFloat16,
f16round,
} from "@petamoriken/float16";
```
### Browser
Deliver a `browser/float16.mjs` or `browser/float16.js` file in the npm package
from your Web server with the JavaScript `Content-Type` HTTP header.
```html
<!-- Module Scripts -->
<script type="module">
import {
Float16Array, isFloat16Array, isTypedArray,
getFloat16, setFloat16,
f16round,
} from "DEST/TO/float16.mjs";
</script>
```
```html
<!-- Classic Scripts -->
<script src="DEST/TO/float16.js"></script>
<script>
const {
Float16Array, isFloat16Array, isTypedArray,
getFloat16, setFloat16,
f16round,
} = float16;
</script>
```
<details>
<summary>Or, you can use <a href="https://www.jsdelivr.com/package/npm/@petamoriken/float16">jsDelivr CDN</a>.</summary>
```html
<!-- Module Scripts -->
<script type="module">
import {
Float16Array, isFloat16Array, isTypedArray,
getFloat16, setFloat16,
f16round,
} from "https://cdn.jsdelivr.net/npm/@petamoriken/float16/+esm";
</script>
```
```html
<!-- Classic Scripts -->
<script src="https://cdn.jsdelivr.net/npm/@petamoriken/float16/browser/float16.min.js"></script>
<script>
const {
Float16Array, isFloat16Array, isTypedArray,
getFloat16, setFloat16,
f16round,
} = float16;
</script>
```
</details>
## Support engines
**This package only requires ES2015 features** and does not use
environment-dependent features (except for `inspect/`), so you can use it
without any problems. It works fine with
[the current officially supported versions of Node.js](https://github.com/nodejs/Release).
`Float16Array` implemented by `Proxy` and `Reflect`, so IE11 is never supported
even if you use polyfills.
### Pre-transpiled JavaScript files (CommonJS, IIFE)
`lib/` and `browser/` directories in the npm package have JavaScript files
already transpiled, and they have been tested automatically in the following
environments:
- Node.js: Active LTS
- Firefox: last 2 versions and ESR
- Chrome: last 2 versions
- Safari: last 2 versions
## API
### `Float16Array`
`Float16Array` is similar to `TypedArray` such as `Float32Array`
([MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array)).
```js
const array = new Float16Array([1.0, 1.1, 1.2, 1.3]);
for (const value of array) {
// 1, 1.099609375, 1.2001953125, 1.2998046875
console.log(value);
}
// Float16Array(4) [ 2, 2.19921875, 2.3984375, 2.599609375 ]
array.map((value) => value * 2);
```
### `isFloat16Array`
> [!WARNING]
> This API returns `false` for ECMAScript's native `Float16Array`
`isFloat16Array` is a utility function to check whether the value given as an
argument is an instance of `Float16Array` or not.
```js
const buffer = new ArrayBuffer(256);
// true
isFloat16Array(new Float16Array(buffer));
// false
isFloat16Array(new Float32Array(buffer));
isFloat16Array(new Uint16Array(buffer));
isFloat16Array(new DataView(buffer));
```
### `isTypedArray`
`isTypedArray` is a utility function to check whether the value given as an
argument is an instance of a type of `TypedArray` or not. Unlike
`util.types.isTypedArray` in Node.js, this returns `true` for `Float16Array`.
```js
const buffer = new ArrayBuffer(256);
// true
isTypedArray(new Float16Array(buffer));
isTypedArray(new Float32Array(buffer));
isTypedArray(new Uint16Array(buffer));
// false
isTypedArray(new DataView(buffer));
```
### `getFloat16`, `setFloat16`
`getFloat16` and `setFloat16` are similar to `DataView` methods such as
`DataView#getFloat32`
([MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView/getFloat32))
and `DataView#setFloat32`
([MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView/setFloat32)).
```ts
declare function getFloat16(view: DataView, byteOffset: number, littleEndian?: boolean): number;
declare function setFloat16(view: DataView, byteOffset: number, value: number, littleEndian?: boolean): void;
```
```js
const buffer = new ArrayBuffer(256);
const view = new DataView(buffer);
view.setUint16(0, 0x1234);
getFloat16(view, 0); // 0.0007572174072265625
// You can append methods to DataView instance
view.getFloat16 = (...args) => getFloat16(view, ...args);
view.setFloat16 = (...args) => setFloat16(view, ...args);
view.getFloat16(0); // 0.0007572174072265625
view.setFloat16(0, Math.PI, true);
view.getFloat16(0, true); // 3.140625
```
### `f16round` (alias: `hfround`)
`f16round` is similar to `Math.fround`
([MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/fround)).
This function returns nearest half-precision float representation of a number.
```ts
declare function f16round(x: number): number;
```
```js
Math.fround(1.337); // 1.3370000123977661
f16round(1.337); // 1.3369140625
```
## `Float16Array` limitations (edge cases)
<details>
<summary><code>Float16Array</code> has some limitations, because it is impossible to completely reproduce the behavior of <code>TypedArray</code>. Be careful when checking if it is a <code>TypedArray</code> or not by using <code>ArrayBuffer.isView</code>, and when using Web standards such as <code>structuredClone</code> and WebGL.</summary>
### Built-in functions
Built-in `TypedArray` objects use "internal slots" for built-in methods. Some
limitations exist because the `Proxy` object can't trap internal slots
([explanation](https://javascript.info/proxy#built-in-objects-internal-slots)).
This package isn't polyfill, in other words, it doesn't change native global
functions and static/prototype methods.
E.g. `ArrayBuffer.isView` is the butlt-in method that checks if it has the
`[[ViewedArrayBuffer]]` internal slot. It returns `false` for `Proxy` object
such as `Float16Array` instance.
```js
ArrayBuffer.isView(new Float32Array(10)); // true
ArrayBuffer.isView(new Float16Array(10)); // false
```
### The structured clone algorithm (Web Workers, IndexedDB, etc)
The structured clone algorithm copies complex JavaScript objects. It is used
internally when invoking `structuredClone()`, to transfer data between Web
Workers via `postMessage()`, storing objects with IndexedDB, or copying objects
for other APIs
([MDN](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm)).
It can't clone `Proxy` object such as `Float16Array` instance, you need to
convert it to `Uint16Array` or deal with `ArrayBuffer` directly.
```js
const array = new Float16Array([1.0, 1.1, 1.2]);
const cloned = structuredClone({ buffer: array.buffer });
```
### WebGL
WebGL requires `Uint16Array` for buffer or texture data whose types are
`gl.HALF_FLOAT` (WebGL 2) or `ext.HALF_FLOAT_OES` (WebGL 1 extension). Do not
apply the `Float16Array` object directly to `gl.bufferData` or `gl.texImage2D`
etc.
```js
// WebGL 2 example
const vertices = new Float16Array([
-0.5, -0.5, 0,
0.5, -0.5, 0,
0.5, 0.5, 0,
]);
const buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
// wrap in Uint16Array
gl.bufferData(gl.ARRAY_BUFFER, new Uint16Array(vertices.buffer), gl.STATIC_DRAW);
gl.vertexAttribPointer(location, 3, gl.HALF_FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, null);
gl.enableVertexAttribArray(location);
```
### Others
See JSDoc comments in `src/Float16Array.mjs` for details. If you don't write
hacky code, you shouldn't have any problems.
</details>
## `Float16Array` custom inspection
<details>
<summary>Provides custom inspection for Node.js and Deno, which makes the results of <code>console.log</code> more readable.
</summary>
```js
import { Float16Array } from "@petamoriken/float16";
import { customInspect } from "@petamoriken/float16/inspect";
Float16Array.prototype[Symbol.for("nodejs.util.inspect.custom")] = customInspect;
```
```ts
import { Float16Array } from "@petamoriken/float16";
import { customInspect } from "@petamoriken/float16/inspect";
// deno-lint-ignore no-explicit-any
(Float16Array.prototype as any)[Symbol.for("nodejs.util.inspect.custom")] = customInspect;
```
</details>
## Development
<details>
<summary>Manual build and test</summary>
### Manual build
This repository uses corepack for package manager manager.
You may have to activate yarn in corepack.
```console
corepack enable yarn
```
Download devDependencies.
```console
yarn
```
Build `lib/`, `browser/` files.
```console
yarn run build
```
Build `docs/` files (for browser test).
```console
yarn run docs
```
### Test
This repository uses corepack for package manager manager.
You may have to activate yarn in corepack.
```console
corepack enable yarn
```
Download devDependencies.
```console
yarn
```
#### Node.js test
```console
NODE_ENV=test yarn build:lib
yarn test
```
#### Browser test
```console
NODE_ENV=test yarn build:browser
yarn docs
```
Access `docs/test/index.html` with browsers.
You can access current [test page](https://petamoriken.github.io/float16/test)
([power-assert version](https://petamoriken.github.io/float16/test/power)) in
`master` branch.
</details>
## License
MIT License
This software contains productions that are distributed under
[the Apache 2.0 License](http://www.apache.org/licenses/LICENSE-2.0).
Specifically, `index.d.ts` is modified from the original
[TypeScript lib files](https://github.com/microsoft/TypeScript/tree/main/src/lib).
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-546
View File
@@ -1,546 +0,0 @@
/**
* A typed array of 16-bit float values. The contents are initialized to 0. If the requested number
* of bytes could not be allocated an exception is raised.
*/
export interface Float16Array {
/**
* The size in bytes of each element in the array.
*/
readonly BYTES_PER_ELEMENT: number;
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
*/
readonly byteLength: number;
/**
* The offset in bytes of the array.
*/
readonly byteOffset: number;
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): number | undefined;
/**
* Returns the this object after copying a section of the array identified by start and end
* to the same array starting at position target
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* is treated as length+end.
* @param end If not specified, length of the this object is used as its default value.
*/
copyWithin(target: number, start: number, end?: number): this;
/**
* Determines whether all the members of an array satisfy the specified test.
* @param predicate A function that accepts up to three arguments. The every method calls
* the predicate function for each element in the array until the predicate returns a value
* which is coercible to the Boolean value false, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the predicate function.
* If thisArg is omitted, undefined is used as the this value.
*/
every(
predicate: (value: number, index: number, array: this) => unknown,
thisArg?: any,
): boolean;
/**
* Changes all array elements from `start` to `end` index to a static `value` and returns the modified array
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* length+end.
*/
fill(value: number, start?: number, end?: number): this;
/**
* Returns the elements of an array that meet the condition specified in a callback function.
* @param predicate A function that accepts up to three arguments. The filter method calls
* the predicate function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the predicate function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(
predicate: (value: number, index: number, array: this) => any,
thisArg?: any,
): Float16Array;
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(
predicate: (value: number, index: number, obj: this) => boolean,
thisArg?: any,
): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and -1
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(
predicate: (value: number, index: number, obj: this) => boolean,
thisArg?: any,
): number;
/**
* Returns the value of the last element in the array where predicate is true, and undefined
* otherwise.
* @param predicate findLast calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found, findLast
* immediately returns that element value. Otherwise, findLast returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findLast<S extends number>(
predicate: (
value: number,
index: number,
array: this,
) => value is S,
thisArg?: any,
): S | undefined;
findLast(
predicate: (
value: number,
index: number,
array: this,
) => unknown,
thisArg?: any,
): number | undefined;
/**
* Returns the index of the last element in the array where predicate is true, and -1
* otherwise.
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found,
* findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findLastIndex(
predicate: (
value: number,
index: number,
array: this,
) => unknown,
thisArg?: any,
): number;
/**
* Performs the specified action for each element in an array.
* @param callbackfn A function that accepts up to three arguments. forEach calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
forEach(
callbackfn: (value: number, index: number, array: this) => void,
thisArg?: any,
): void;
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
/**
* Returns the index of the first occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
indexOf(searchElement: number, fromIndex?: number): number;
/**
* Adds all the elements of an array separated by the specified separator string.
* @param separator A string used to separate one element of an array from the next in the
* resulting String. If omitted, the array elements are separated with a comma.
*/
join(separator?: string): string;
/**
* Returns the index of the last occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
lastIndexOf(searchElement: number, fromIndex?: number): number;
/**
* The length of the array.
*/
readonly length: number;
/**
* Calls a defined callback function on each element of an array, and returns an array that
* contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
map(
callbackfn: (value: number, index: number, array: this) => number,
thisArg?: any,
): Float16Array;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce(
callbackfn: (
previousValue: number,
currentValue: number,
currentIndex: number,
array: this,
) => number,
): number;
reduce(
callbackfn: (
previousValue: number,
currentValue: number,
currentIndex: number,
array: this,
) => number,
initialValue: number,
): number;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce<U>(
callbackfn: (
previousValue: U,
currentValue: number,
currentIndex: number,
array: this,
) => U,
initialValue: U,
): U;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* The return value of the callback function is the accumulated result, and is provided as an
* argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
* the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an
* argument instead of an array value.
*/
reduceRight(
callbackfn: (
previousValue: number,
currentValue: number,
currentIndex: number,
array: this,
) => number,
): number;
reduceRight(
callbackfn: (
previousValue: number,
currentValue: number,
currentIndex: number,
array: this,
) => number,
initialValue: number,
): number;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* The return value of the callback function is the accumulated result, and is provided as an
* argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
* the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduceRight<U>(
callbackfn: (
previousValue: U,
currentValue: number,
currentIndex: number,
array: this,
) => U,
initialValue: U,
): U;
/**
* Reverses the elements in an Array.
*/
reverse(): this;
/**
* Sets a value or an array of values.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: ArrayLike<number>, offset?: number): void;
/**
* Returns a section of an array.
* @param start The beginning of the specified portion of the array.
* @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.
*/
slice(start?: number, end?: number): Float16Array;
/**
* Determines whether the specified callback function returns true for any element of an array.
* @param predicate A function that accepts up to three arguments. The some method calls
* the predicate function for each element in the array until the predicate returns a value
* which is coercible to the Boolean value true, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the predicate function.
* If thisArg is omitted, undefined is used as the this value.
*/
some(
predicate: (value: number, index: number, array: this) => unknown,
thisArg?: any,
): boolean;
/**
* Sorts an array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if first argument is less than second argument, zero if they're equal and a positive
* value otherwise. If omitted, the elements are sorted in ascending order.
* ```ts
* [11,2,22,1].sort((a, b) => a - b)
* ```
*/
sort(compareFn?: (a: number, b: number) => number): this;
/**
* Gets a new Float16Array view of the ArrayBuffer store for this array, referencing the elements
* at begin, inclusive, up to end, exclusive.
* @param begin The index of the beginning of the array.
* @param end The index of the end of the array.
*/
subarray(begin?: number, end?: number): Float16Array;
/**
* Converts a number to a string by using the current locale.
*/
toLocaleString(
locales?: string | string[],
options?: Intl.NumberFormatOptions,
): string;
/**
* Copies the array and returns the copy with the elements in reverse order.
*/
toReversed(): Float16Array;
/**
* Copies and sorts the array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
* value otherwise. If omitted, the elements are sorted in ascending order.
* ```ts
* const myNums = Float16Array.from([11.25, 2, -22.5, 1]);
* myNums.toSorted((a, b) => a - b) // Float16Array(4) [-22.5, 1, 2, 11.5]
* ```
*/
toSorted(compareFn?: (a: number, b: number) => number): Float16Array;
/**
* Returns a string representation of an array.
*/
toString(): string;
/** Returns the primitive value of the specified object. */
valueOf(): this;
/**
* Copies the array and inserts the given number at the provided index.
* @param index The index of the value to overwrite. If the index is
* negative, then it replaces from the end of the array.
* @param value The value to insert into the copied array.
* @returns A copy of the original array with the inserted value.
*/
with(index: number, value: number): Float16Array;
[index: number]: number;
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Float16Array";
}
export interface Float16ArrayConstructor {
readonly prototype: Float16Array;
new (length?: number): Float16Array;
new (array: ArrayLike<number> | Iterable<number>): Float16Array;
new (
buffer: ArrayBufferLike,
byteOffset?: number,
length?: number,
): Float16Array;
/**
* The size in bytes of each element in the array.
*/
readonly BYTES_PER_ELEMENT: number;
/**
* Returns a new array from a set of elements.
* @param items A set of elements to include in the new array object.
*/
of(...items: number[]): Float16Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like object to convert to an array.
*/
from(arrayLike: ArrayLike<number>): Float16Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T>(
arrayLike: ArrayLike<T>,
mapfn: (v: T, k: number) => number,
thisArg?: any,
): Float16Array;
/**
* Creates an array from an array-like or iterable object.
* @param elements An iterable object to convert to an array.
*/
from(elements: Iterable<number>): Float16Array;
/**
* Creates an array from an array-like or iterable object.
* @param elements An iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T>(
elements: Iterable<T>,
mapfn?: (v: T, k: number) => number,
thisArg?: any,
): Float16Array;
}
export declare const Float16Array: Float16ArrayConstructor;
/**
* Returns `true` if the value is a Float16Array instance.
*
* WARNING: This API returns `false` for ECMAScript's native Float16Array
* @since v3.4.0
*/
export declare function isFloat16Array(value: unknown): value is Float16Array;
/**
* Returns `true` if the value is a type of TypedArray instance that contains Float16Array.
* @since v3.6.0
*/
export declare function isTypedArray(
value: unknown,
): value is
| Uint8Array
| Uint8ClampedArray
| Uint16Array
| Uint32Array
| Int8Array
| Int16Array
| Int32Array
| Float16Array
| Float32Array
| Float64Array
| BigUint64Array
| BigInt64Array;
/**
* Gets the Float16 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
* @param littleEndian If false or undefined, a big-endian value should be read,
* otherwise a little-endian value should be read.
*/
export declare function getFloat16(
dataView: DataView,
byteOffset: number,
littleEndian?: boolean,
): number;
/**
* Stores an Float16 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
export declare function setFloat16(
dataView: DataView,
byteOffset: number,
value: number,
littleEndian?: boolean,
): void;
/**
* Returns the nearest half-precision float representation of a number.
* @param x A numeric expression.
*/
export declare function f16round(x: number): number;
/**
* Returns the nearest half-precision float representation of a number.
* @alias f16round
* @param x A numeric expression.
*/
export declare function hfround(x: number): number;
-546
View File
@@ -1,546 +0,0 @@
/**
* A typed array of 16-bit float values. The contents are initialized to 0. If the requested number
* of bytes could not be allocated an exception is raised.
*/
export interface Float16Array {
/**
* The size in bytes of each element in the array.
*/
readonly BYTES_PER_ELEMENT: number;
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
*/
readonly byteLength: number;
/**
* The offset in bytes of the array.
*/
readonly byteOffset: number;
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): number | undefined;
/**
* Returns the this object after copying a section of the array identified by start and end
* to the same array starting at position target
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* is treated as length+end.
* @param end If not specified, length of the this object is used as its default value.
*/
copyWithin(target: number, start: number, end?: number): this;
/**
* Determines whether all the members of an array satisfy the specified test.
* @param predicate A function that accepts up to three arguments. The every method calls
* the predicate function for each element in the array until the predicate returns a value
* which is coercible to the Boolean value false, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the predicate function.
* If thisArg is omitted, undefined is used as the this value.
*/
every(
predicate: (value: number, index: number, array: this) => unknown,
thisArg?: any,
): boolean;
/**
* Changes all array elements from `start` to `end` index to a static `value` and returns the modified array
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* length+end.
*/
fill(value: number, start?: number, end?: number): this;
/**
* Returns the elements of an array that meet the condition specified in a callback function.
* @param predicate A function that accepts up to three arguments. The filter method calls
* the predicate function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the predicate function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(
predicate: (value: number, index: number, array: this) => any,
thisArg?: any,
): Float16Array;
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(
predicate: (value: number, index: number, obj: this) => boolean,
thisArg?: any,
): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and -1
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(
predicate: (value: number, index: number, obj: this) => boolean,
thisArg?: any,
): number;
/**
* Returns the value of the last element in the array where predicate is true, and undefined
* otherwise.
* @param predicate findLast calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found, findLast
* immediately returns that element value. Otherwise, findLast returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findLast<S extends number>(
predicate: (
value: number,
index: number,
array: this,
) => value is S,
thisArg?: any,
): S | undefined;
findLast(
predicate: (
value: number,
index: number,
array: this,
) => unknown,
thisArg?: any,
): number | undefined;
/**
* Returns the index of the last element in the array where predicate is true, and -1
* otherwise.
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found,
* findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findLastIndex(
predicate: (
value: number,
index: number,
array: this,
) => unknown,
thisArg?: any,
): number;
/**
* Performs the specified action for each element in an array.
* @param callbackfn A function that accepts up to three arguments. forEach calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
forEach(
callbackfn: (value: number, index: number, array: this) => void,
thisArg?: any,
): void;
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
/**
* Returns the index of the first occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
indexOf(searchElement: number, fromIndex?: number): number;
/**
* Adds all the elements of an array separated by the specified separator string.
* @param separator A string used to separate one element of an array from the next in the
* resulting String. If omitted, the array elements are separated with a comma.
*/
join(separator?: string): string;
/**
* Returns the index of the last occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
lastIndexOf(searchElement: number, fromIndex?: number): number;
/**
* The length of the array.
*/
readonly length: number;
/**
* Calls a defined callback function on each element of an array, and returns an array that
* contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
map(
callbackfn: (value: number, index: number, array: this) => number,
thisArg?: any,
): Float16Array;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce(
callbackfn: (
previousValue: number,
currentValue: number,
currentIndex: number,
array: this,
) => number,
): number;
reduce(
callbackfn: (
previousValue: number,
currentValue: number,
currentIndex: number,
array: this,
) => number,
initialValue: number,
): number;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce<U>(
callbackfn: (
previousValue: U,
currentValue: number,
currentIndex: number,
array: this,
) => U,
initialValue: U,
): U;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* The return value of the callback function is the accumulated result, and is provided as an
* argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
* the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an
* argument instead of an array value.
*/
reduceRight(
callbackfn: (
previousValue: number,
currentValue: number,
currentIndex: number,
array: this,
) => number,
): number;
reduceRight(
callbackfn: (
previousValue: number,
currentValue: number,
currentIndex: number,
array: this,
) => number,
initialValue: number,
): number;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* The return value of the callback function is the accumulated result, and is provided as an
* argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
* the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduceRight<U>(
callbackfn: (
previousValue: U,
currentValue: number,
currentIndex: number,
array: this,
) => U,
initialValue: U,
): U;
/**
* Reverses the elements in an Array.
*/
reverse(): this;
/**
* Sets a value or an array of values.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: ArrayLike<number>, offset?: number): void;
/**
* Returns a section of an array.
* @param start The beginning of the specified portion of the array.
* @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.
*/
slice(start?: number, end?: number): Float16Array;
/**
* Determines whether the specified callback function returns true for any element of an array.
* @param predicate A function that accepts up to three arguments. The some method calls
* the predicate function for each element in the array until the predicate returns a value
* which is coercible to the Boolean value true, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the predicate function.
* If thisArg is omitted, undefined is used as the this value.
*/
some(
predicate: (value: number, index: number, array: this) => unknown,
thisArg?: any,
): boolean;
/**
* Sorts an array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if first argument is less than second argument, zero if they're equal and a positive
* value otherwise. If omitted, the elements are sorted in ascending order.
* ```ts
* [11,2,22,1].sort((a, b) => a - b)
* ```
*/
sort(compareFn?: (a: number, b: number) => number): this;
/**
* Gets a new Float16Array view of the ArrayBuffer store for this array, referencing the elements
* at begin, inclusive, up to end, exclusive.
* @param begin The index of the beginning of the array.
* @param end The index of the end of the array.
*/
subarray(begin?: number, end?: number): Float16Array;
/**
* Converts a number to a string by using the current locale.
*/
toLocaleString(
locales?: string | string[],
options?: Intl.NumberFormatOptions,
): string;
/**
* Copies the array and returns the copy with the elements in reverse order.
*/
toReversed(): Float16Array;
/**
* Copies and sorts the array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
* value otherwise. If omitted, the elements are sorted in ascending order.
* ```ts
* const myNums = Float16Array.from([11.25, 2, -22.5, 1]);
* myNums.toSorted((a, b) => a - b) // Float16Array(4) [-22.5, 1, 2, 11.5]
* ```
*/
toSorted(compareFn?: (a: number, b: number) => number): Float16Array;
/**
* Returns a string representation of an array.
*/
toString(): string;
/** Returns the primitive value of the specified object. */
valueOf(): this;
/**
* Copies the array and inserts the given number at the provided index.
* @param index The index of the value to overwrite. If the index is
* negative, then it replaces from the end of the array.
* @param value The value to insert into the copied array.
* @returns A copy of the original array with the inserted value.
*/
with(index: number, value: number): Float16Array;
[index: number]: number;
[Symbol.iterator](): ArrayIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): ArrayIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): ArrayIterator<number>;
/**
* Returns an list of values in the array
*/
values(): ArrayIterator<number>;
readonly [Symbol.toStringTag]: "Float16Array";
}
export interface Float16ArrayConstructor {
readonly prototype: Float16Array;
new (length?: number): Float16Array;
new (array: ArrayLike<number> | Iterable<number>): Float16Array;
new (
buffer: ArrayBufferLike,
byteOffset?: number,
length?: number,
): Float16Array;
/**
* The size in bytes of each element in the array.
*/
readonly BYTES_PER_ELEMENT: number;
/**
* Returns a new array from a set of elements.
* @param items A set of elements to include in the new array object.
*/
of(...items: number[]): Float16Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like object to convert to an array.
*/
from(arrayLike: ArrayLike<number>): Float16Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T>(
arrayLike: ArrayLike<T>,
mapfn: (v: T, k: number) => number,
thisArg?: any,
): Float16Array;
/**
* Creates an array from an array-like or iterable object.
* @param elements An iterable object to convert to an array.
*/
from(elements: Iterable<number>): Float16Array;
/**
* Creates an array from an array-like or iterable object.
* @param elements An iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T>(
elements: Iterable<T>,
mapfn?: (v: T, k: number) => number,
thisArg?: any,
): Float16Array;
}
export declare const Float16Array: Float16ArrayConstructor;
/**
* Returns `true` if the value is a Float16Array instance.
*
* WARNING: This API returns `false` for ECMAScript's native Float16Array
* @since v3.4.0
*/
export declare function isFloat16Array(value: unknown): value is Float16Array;
/**
* Returns `true` if the value is a type of TypedArray instance that contains Float16Array.
* @since v3.6.0
*/
export declare function isTypedArray(
value: unknown,
): value is
| Uint8Array
| Uint8ClampedArray
| Uint16Array
| Uint32Array
| Int8Array
| Int16Array
| Int32Array
| Float16Array
| Float32Array
| Float64Array
| BigUint64Array
| BigInt64Array;
/**
* Gets the Float16 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
* @param littleEndian If false or undefined, a big-endian value should be read,
* otherwise a little-endian value should be read.
*/
export declare function getFloat16(
dataView: DataView,
byteOffset: number,
littleEndian?: boolean,
): number;
/**
* Stores an Float16 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
export declare function setFloat16(
dataView: DataView,
byteOffset: number,
value: number,
littleEndian?: boolean,
): void;
/**
* Returns the nearest half-precision float representation of a number.
* @param x A numeric expression.
*/
export declare function f16round(x: number): number;
/**
* Returns the nearest half-precision float representation of a number.
* @alias f16round
* @param x A numeric expression.
*/
export declare function hfround(x: number): number;
-555
View File
@@ -1,555 +0,0 @@
/**
* A typed array of 16-bit float values. The contents are initialized to 0. If the requested number
* of bytes could not be allocated an exception is raised.
*/
export interface Float16Array<
TArrayBuffer extends ArrayBufferLike = ArrayBufferLike,
> {
/**
* The size in bytes of each element in the array.
*/
readonly BYTES_PER_ELEMENT: number;
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: TArrayBuffer;
/**
* The length in bytes of the array.
*/
readonly byteLength: number;
/**
* The offset in bytes of the array.
*/
readonly byteOffset: number;
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): number | undefined;
/**
* Returns the this object after copying a section of the array identified by start and end
* to the same array starting at position target
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* is treated as length+end.
* @param end If not specified, length of the this object is used as its default value.
*/
copyWithin(target: number, start: number, end?: number): this;
/**
* Determines whether all the members of an array satisfy the specified test.
* @param predicate A function that accepts up to three arguments. The every method calls
* the predicate function for each element in the array until the predicate returns a value
* which is coercible to the Boolean value false, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the predicate function.
* If thisArg is omitted, undefined is used as the this value.
*/
every(
predicate: (value: number, index: number, array: this) => unknown,
thisArg?: any,
): boolean;
/**
* Changes all array elements from `start` to `end` index to a static `value` and returns the modified array
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* length+end.
*/
fill(value: number, start?: number, end?: number): this;
/**
* Returns the elements of an array that meet the condition specified in a callback function.
* @param predicate A function that accepts up to three arguments. The filter method calls
* the predicate function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the predicate function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(
predicate: (value: number, index: number, array: this) => any,
thisArg?: any,
): Float16Array<ArrayBuffer>;
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(
predicate: (value: number, index: number, obj: this) => boolean,
thisArg?: any,
): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and -1
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(
predicate: (value: number, index: number, obj: this) => boolean,
thisArg?: any,
): number;
/**
* Returns the value of the last element in the array where predicate is true, and undefined
* otherwise.
* @param predicate findLast calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found, findLast
* immediately returns that element value. Otherwise, findLast returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findLast<S extends number>(
predicate: (
value: number,
index: number,
array: this,
) => value is S,
thisArg?: any,
): S | undefined;
findLast(
predicate: (
value: number,
index: number,
array: this,
) => unknown,
thisArg?: any,
): number | undefined;
/**
* Returns the index of the last element in the array where predicate is true, and -1
* otherwise.
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found,
* findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findLastIndex(
predicate: (
value: number,
index: number,
array: this,
) => unknown,
thisArg?: any,
): number;
/**
* Performs the specified action for each element in an array.
* @param callbackfn A function that accepts up to three arguments. forEach calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
forEach(
callbackfn: (value: number, index: number, array: this) => void,
thisArg?: any,
): void;
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
/**
* Returns the index of the first occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
indexOf(searchElement: number, fromIndex?: number): number;
/**
* Adds all the elements of an array separated by the specified separator string.
* @param separator A string used to separate one element of an array from the next in the
* resulting String. If omitted, the array elements are separated with a comma.
*/
join(separator?: string): string;
/**
* Returns the index of the last occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
lastIndexOf(searchElement: number, fromIndex?: number): number;
/**
* The length of the array.
*/
readonly length: number;
/**
* Calls a defined callback function on each element of an array, and returns an array that
* contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
map(
callbackfn: (value: number, index: number, array: this) => number,
thisArg?: any,
): Float16Array<ArrayBuffer>;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce(
callbackfn: (
previousValue: number,
currentValue: number,
currentIndex: number,
array: this,
) => number,
): number;
reduce(
callbackfn: (
previousValue: number,
currentValue: number,
currentIndex: number,
array: this,
) => number,
initialValue: number,
): number;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce<U>(
callbackfn: (
previousValue: U,
currentValue: number,
currentIndex: number,
array: this,
) => U,
initialValue: U,
): U;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* The return value of the callback function is the accumulated result, and is provided as an
* argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
* the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an
* argument instead of an array value.
*/
reduceRight(
callbackfn: (
previousValue: number,
currentValue: number,
currentIndex: number,
array: this,
) => number,
): number;
reduceRight(
callbackfn: (
previousValue: number,
currentValue: number,
currentIndex: number,
array: this,
) => number,
initialValue: number,
): number;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* The return value of the callback function is the accumulated result, and is provided as an
* argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
* the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduceRight<U>(
callbackfn: (
previousValue: U,
currentValue: number,
currentIndex: number,
array: this,
) => U,
initialValue: U,
): U;
/**
* Reverses the elements in an Array.
*/
reverse(): this;
/**
* Sets a value or an array of values.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: ArrayLike<number>, offset?: number): void;
/**
* Returns a section of an array.
* @param start The beginning of the specified portion of the array.
* @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.
*/
slice(start?: number, end?: number): Float16Array<ArrayBuffer>;
/**
* Determines whether the specified callback function returns true for any element of an array.
* @param predicate A function that accepts up to three arguments. The some method calls
* the predicate function for each element in the array until the predicate returns a value
* which is coercible to the Boolean value true, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the predicate function.
* If thisArg is omitted, undefined is used as the this value.
*/
some(
predicate: (value: number, index: number, array: this) => unknown,
thisArg?: any,
): boolean;
/**
* Sorts an array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if first argument is less than second argument, zero if they're equal and a positive
* value otherwise. If omitted, the elements are sorted in ascending order.
* ```ts
* [11,2,22,1].sort((a, b) => a - b)
* ```
*/
sort(compareFn?: (a: number, b: number) => number): this;
/**
* Gets a new Float16Array view of the ArrayBuffer store for this array, referencing the elements
* at begin, inclusive, up to end, exclusive.
* @param begin The index of the beginning of the array.
* @param end The index of the end of the array.
*/
subarray(begin?: number, end?: number): Float16Array<TArrayBuffer>;
/**
* Converts a number to a string by using the current locale.
*/
toLocaleString(
locales?: string | string[],
options?: Intl.NumberFormatOptions,
): string;
/**
* Copies the array and returns the copy with the elements in reverse order.
*/
toReversed(): Float16Array<ArrayBuffer>;
/**
* Copies and sorts the array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
* value otherwise. If omitted, the elements are sorted in ascending order.
* ```ts
* const myNums = Float16Array.from([11.25, 2, -22.5, 1]);
* myNums.toSorted((a, b) => a - b) // Float16Array(4) [-22.5, 1, 2, 11.5]
* ```
*/
toSorted(
compareFn?: (a: number, b: number) => number,
): Float16Array<ArrayBuffer>;
/**
* Returns a string representation of an array.
*/
toString(): string;
/** Returns the primitive value of the specified object. */
valueOf(): this;
/**
* Copies the array and inserts the given number at the provided index.
* @param index The index of the value to overwrite. If the index is
* negative, then it replaces from the end of the array.
* @param value The value to insert into the copied array.
* @returns A copy of the original array with the inserted value.
*/
with(index: number, value: number): Float16Array<ArrayBuffer>;
[index: number]: number;
[Symbol.iterator](): ArrayIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): ArrayIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): ArrayIterator<number>;
/**
* Returns an list of values in the array
*/
values(): ArrayIterator<number>;
readonly [Symbol.toStringTag]: "Float16Array";
}
export interface Float16ArrayConstructor {
readonly prototype: Float16Array<ArrayBufferLike>;
new (length?: number): Float16Array<ArrayBuffer>;
new (array: ArrayLike<number> | Iterable<number>): Float16Array<ArrayBuffer>;
new <TArrayBuffer extends ArrayBufferLike = ArrayBuffer>(
buffer: TArrayBuffer,
byteOffset?: number,
length?: number,
): Float16Array<TArrayBuffer>;
/**
* The size in bytes of each element in the array.
*/
readonly BYTES_PER_ELEMENT: number;
/**
* Returns a new array from a set of elements.
* @param items A set of elements to include in the new array object.
*/
of(...items: number[]): Float16Array<ArrayBuffer>;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like object to convert to an array.
*/
from(arrayLike: ArrayLike<number>): Float16Array<ArrayBuffer>;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T>(
arrayLike: ArrayLike<T>,
mapfn: (v: T, k: number) => number,
thisArg?: any,
): Float16Array<ArrayBuffer>;
/**
* Creates an array from an array-like or iterable object.
* @param elements An iterable object to convert to an array.
*/
from(elements: Iterable<number>): Float16Array<ArrayBuffer>;
/**
* Creates an array from an array-like or iterable object.
* @param elements An iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T>(
elements: Iterable<T>,
mapfn?: (v: T, k: number) => number,
thisArg?: any,
): Float16Array<ArrayBuffer>;
}
export declare const Float16Array: Float16ArrayConstructor;
/**
* Returns `true` if the value is a Float16Array instance.
*
* WARNING: This API returns `false` for ECMAScript's native Float16Array
* @since v3.4.0
*/
export declare function isFloat16Array(value: unknown): value is Float16Array;
/**
* Returns `true` if the value is a type of TypedArray instance that contains Float16Array.
*
* @since v3.6.0
*/
export declare function isTypedArray(
value: unknown,
): value is
| Uint8Array<ArrayBufferLike>
| Uint8ClampedArray<ArrayBufferLike>
| Uint16Array<ArrayBufferLike>
| Uint32Array<ArrayBufferLike>
| Int8Array<ArrayBufferLike>
| Int16Array<ArrayBufferLike>
| Int32Array<ArrayBufferLike>
| Float16Array<ArrayBufferLike>
| Float32Array<ArrayBufferLike>
| Float64Array<ArrayBufferLike>
| BigUint64Array<ArrayBufferLike>
| BigInt64Array<ArrayBufferLike>;
/**
* Gets the Float16 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
*
* @param byteOffset The place in the buffer at which the value should be retrieved.
* @param littleEndian If false or undefined, a big-endian value should be read,
* otherwise a little-endian value should be read.
*/
export declare function getFloat16(
dataView: DataView<ArrayBufferLike>,
byteOffset: number,
littleEndian?: boolean,
): number;
/**
* Stores an Float16 value at the specified byte offset from the start of the view.
*
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
export declare function setFloat16(
dataView: DataView<ArrayBufferLike>,
byteOffset: number,
value: number,
littleEndian?: boolean,
): void;
/**
* Returns the nearest half-precision float representation of a number.
*
* @param x A numeric expression.
*/
export declare function f16round(x: number): number;
/**
* Returns the nearest half-precision float representation of a number.
*
* @alias f16round
* @param x A numeric expression.
*/
export declare function hfround(x: number): number;
-25
View File
@@ -1,25 +0,0 @@
/* eslint-env node */
"use strict";
/**
* Custom inspect function for Node.js, Deno, and Bun
*
* ```
* Float16Array.prototype[Symbol.for("nodejs.util.inspect.custom")] = customInspect;
* ```
* @param {number} _deps
* @param {import("node:util").InspectOptions} options
* @param {import("node:util").inspect} inspect
* @returns {string}
*/
exports.customInspect = function customInspect(_deps, options, inspect) {
const length = this.length;
const array = [];
for (let i = 0; i < length; ++i) {
array[i] = this[i];
}
return `Float16Array(${length}) ${inspect(array, options)}`;
};
-23
View File
@@ -1,23 +0,0 @@
/* eslint-env node */
/**
* Custom inspect function for Node.js, Deno, and Bun
*
* ```
* Float16Array.prototype[Symbol.for("nodejs.util.inspect.custom")] = customInspect;
* ```
* @param {number} _deps
* @param {import("node:util").InspectOptions} options
* @param {import("node:util").inspect} inspect
* @returns {string}
*/
export function customInspect(_deps, options, inspect) {
const length = this.length;
const array = [];
for (let i = 0; i < length; ++i) {
array[i] = this[i];
}
return `Float16Array(${length}) ${inspect(array, options)}`;
}
-16
View File
@@ -1,16 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getFloat16 = getFloat16;
exports.setFloat16 = setFloat16;
var _arrayIterator = require("./_util/arrayIterator.cjs");
var _converter = require("./_util/converter.cjs");
var _primordials = require("./_util/primordials.cjs");
function getFloat16(dataView, byteOffset, ...opts) {
return (0, _converter.convertToNumber)((0, _primordials.DataViewPrototypeGetUint16)(dataView, byteOffset, ...(0, _arrayIterator.safeIfNeeded)(opts)));
}
function setFloat16(dataView, byteOffset, value, ...opts) {
return (0, _primordials.DataViewPrototypeSetUint16)(dataView, byteOffset, (0, _converter.roundToFloat16Bits)(value), ...(0, _arrayIterator.safeIfNeeded)(opts));
}
-690
View File
@@ -1,690 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isFloat16Array = isFloat16Array;
var _arrayIterator = require("./_util/arrayIterator.cjs");
var _brand = require("./_util/brand.cjs");
var _converter = require("./_util/converter.cjs");
var _is = require("./_util/is.cjs");
var _messages = require("./_util/messages.cjs");
var _primordials = require("./_util/primordials.cjs");
var _spec = require("./_util/spec.cjs");
const BYTES_PER_ELEMENT = 2;
const float16bitsArrays = new _primordials.NativeWeakMap();
function isFloat16Array(target) {
return (0, _primordials.WeakMapPrototypeHas)(float16bitsArrays, target) || !(0, _primordials.ArrayBufferIsView)(target) && (0, _brand.hasFloat16ArrayBrand)(target);
}
function assertFloat16Array(target) {
if (!isFloat16Array(target)) {
throw (0, _primordials.NativeTypeError)(_messages.THIS_IS_NOT_A_FLOAT16ARRAY_OBJECT);
}
}
function assertSpeciesTypedArray(target, count) {
const isTargetFloat16Array = isFloat16Array(target);
const isTargetTypedArray = (0, _is.isNativeTypedArray)(target);
if (!isTargetFloat16Array && !isTargetTypedArray) {
throw (0, _primordials.NativeTypeError)(_messages.SPECIES_CONSTRUCTOR_DIDNT_RETURN_TYPEDARRAY_OBJECT);
}
if (typeof count === "number") {
let length;
if (isTargetFloat16Array) {
const float16bitsArray = getFloat16BitsArray(target);
length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
} else {
length = (0, _primordials.TypedArrayPrototypeGetLength)(target);
}
if (length < count) {
throw (0, _primordials.NativeTypeError)(_messages.DERIVED_CONSTRUCTOR_CREATED_TYPEDARRAY_OBJECT_WHICH_WAS_TOO_SMALL_LENGTH);
}
}
if ((0, _is.isNativeBigIntTypedArray)(target)) {
throw (0, _primordials.NativeTypeError)(_messages.CANNOT_MIX_BIGINT_AND_OTHER_TYPES);
}
}
function getFloat16BitsArray(float16) {
const float16bitsArray = (0, _primordials.WeakMapPrototypeGet)(float16bitsArrays, float16);
if (float16bitsArray !== undefined) {
const buffer = (0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray);
if ((0, _spec.IsDetachedBuffer)(buffer)) {
throw (0, _primordials.NativeTypeError)(_messages.ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER);
}
return float16bitsArray;
}
const buffer = float16.buffer;
if ((0, _spec.IsDetachedBuffer)(buffer)) {
throw (0, _primordials.NativeTypeError)(_messages.ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER);
}
const cloned = (0, _primordials.ReflectConstruct)(Float16Array, [buffer, float16.byteOffset, float16.length], float16.constructor);
return (0, _primordials.WeakMapPrototypeGet)(float16bitsArrays, cloned);
}
function copyToArray(float16bitsArray) {
const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
const array = [];
for (let i = 0; i < length; ++i) {
array[i] = (0, _converter.convertToNumber)(float16bitsArray[i]);
}
return array;
}
const TypedArrayPrototypeGetters = new _primordials.NativeWeakSet();
for (const key of (0, _primordials.ReflectOwnKeys)(_primordials.TypedArrayPrototype)) {
if (key === _primordials.SymbolToStringTag) {
continue;
}
const descriptor = (0, _primordials.ReflectGetOwnPropertyDescriptor)(_primordials.TypedArrayPrototype, key);
if ((0, _primordials.ObjectHasOwn)(descriptor, "get") && typeof descriptor.get === "function") {
(0, _primordials.WeakSetPrototypeAdd)(TypedArrayPrototypeGetters, descriptor.get);
}
}
const handler = (0, _primordials.ObjectFreeze)({
get(target, key, receiver) {
if ((0, _is.isCanonicalIntegerIndexString)(key) && (0, _primordials.ObjectHasOwn)(target, key)) {
return (0, _converter.convertToNumber)((0, _primordials.ReflectGet)(target, key));
}
if ((0, _primordials.WeakSetPrototypeHas)(TypedArrayPrototypeGetters, (0, _primordials.ObjectPrototype__lookupGetter__)(target, key))) {
return (0, _primordials.ReflectGet)(target, key);
}
return (0, _primordials.ReflectGet)(target, key, receiver);
},
set(target, key, value, receiver) {
if ((0, _is.isCanonicalIntegerIndexString)(key) && (0, _primordials.ObjectHasOwn)(target, key)) {
return (0, _primordials.ReflectSet)(target, key, (0, _converter.roundToFloat16Bits)(value));
}
return (0, _primordials.ReflectSet)(target, key, value, receiver);
},
getOwnPropertyDescriptor(target, key) {
if ((0, _is.isCanonicalIntegerIndexString)(key) && (0, _primordials.ObjectHasOwn)(target, key)) {
const descriptor = (0, _primordials.ReflectGetOwnPropertyDescriptor)(target, key);
descriptor.value = (0, _converter.convertToNumber)(descriptor.value);
return descriptor;
}
return (0, _primordials.ReflectGetOwnPropertyDescriptor)(target, key);
},
defineProperty(target, key, descriptor) {
if ((0, _is.isCanonicalIntegerIndexString)(key) && (0, _primordials.ObjectHasOwn)(target, key) && (0, _primordials.ObjectHasOwn)(descriptor, "value")) {
descriptor.value = (0, _converter.roundToFloat16Bits)(descriptor.value);
return (0, _primordials.ReflectDefineProperty)(target, key, descriptor);
}
return (0, _primordials.ReflectDefineProperty)(target, key, descriptor);
}
});
class Float16Array {
constructor(input, _byteOffset, _length) {
let float16bitsArray;
if (isFloat16Array(input)) {
float16bitsArray = (0, _primordials.ReflectConstruct)(_primordials.NativeUint16Array, [getFloat16BitsArray(input)], new.target);
} else if ((0, _is.isObject)(input) && !(0, _is.isAnyArrayBuffer)(input)) {
let list;
let length;
if ((0, _is.isNativeTypedArray)(input)) {
list = input;
length = (0, _primordials.TypedArrayPrototypeGetLength)(input);
const buffer = (0, _primordials.TypedArrayPrototypeGetBuffer)(input);
if ((0, _spec.IsDetachedBuffer)(buffer)) {
throw (0, _primordials.NativeTypeError)(_messages.ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER);
}
if ((0, _is.isNativeBigIntTypedArray)(input)) {
throw (0, _primordials.NativeTypeError)(_messages.CANNOT_MIX_BIGINT_AND_OTHER_TYPES);
}
const data = new _primordials.NativeArrayBuffer(length * BYTES_PER_ELEMENT);
float16bitsArray = (0, _primordials.ReflectConstruct)(_primordials.NativeUint16Array, [data], new.target);
} else {
const iterator = input[_primordials.SymbolIterator];
if (iterator != null && typeof iterator !== "function") {
throw (0, _primordials.NativeTypeError)(_messages.ITERATOR_PROPERTY_IS_NOT_CALLABLE);
}
if (iterator != null) {
if ((0, _is.isOrdinaryArray)(input)) {
list = input;
length = input.length;
} else {
list = [...(input)];
length = list.length;
}
} else {
list = input;
length = (0, _spec.ToLength)(list.length);
}
float16bitsArray = (0, _primordials.ReflectConstruct)(_primordials.NativeUint16Array, [length], new.target);
}
for (let i = 0; i < length; ++i) {
float16bitsArray[i] = (0, _converter.roundToFloat16Bits)(list[i]);
}
} else {
float16bitsArray = (0, _primordials.ReflectConstruct)(_primordials.NativeUint16Array, arguments, new.target);
}
const proxy = new _primordials.NativeProxy(float16bitsArray, handler);
(0, _primordials.WeakMapPrototypeSet)(float16bitsArrays, proxy, float16bitsArray);
return proxy;
}
static from(src, ...opts) {
const Constructor = this;
if (!(0, _primordials.ReflectHas)(Constructor, _brand.brand)) {
throw (0, _primordials.NativeTypeError)(_messages.THIS_CONSTRUCTOR_IS_NOT_A_SUBCLASS_OF_FLOAT16ARRAY);
}
if (Constructor === Float16Array) {
if (isFloat16Array(src) && opts.length === 0) {
const float16bitsArray = getFloat16BitsArray(src);
const uint16 = new _primordials.NativeUint16Array((0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetByteOffset)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray));
return new Float16Array((0, _primordials.TypedArrayPrototypeGetBuffer)((0, _primordials.TypedArrayPrototypeSlice)(uint16)));
}
if (opts.length === 0) {
return new Float16Array((0, _primordials.TypedArrayPrototypeGetBuffer)((0, _primordials.Uint16ArrayFrom)(src, _converter.roundToFloat16Bits)));
}
const mapFunc = opts[0];
const thisArg = opts[1];
return new Float16Array((0, _primordials.TypedArrayPrototypeGetBuffer)((0, _primordials.Uint16ArrayFrom)(src, function (val, ...args) {
return (0, _converter.roundToFloat16Bits)((0, _primordials.ReflectApply)(mapFunc, this, [val, ...(0, _arrayIterator.safeIfNeeded)(args)]));
}, thisArg)));
}
let list;
let length;
const iterator = src[_primordials.SymbolIterator];
if (iterator != null && typeof iterator !== "function") {
throw (0, _primordials.NativeTypeError)(_messages.ITERATOR_PROPERTY_IS_NOT_CALLABLE);
}
if (iterator != null) {
if ((0, _is.isOrdinaryArray)(src)) {
list = src;
length = src.length;
} else if ((0, _is.isOrdinaryNativeTypedArray)(src)) {
list = src;
length = (0, _primordials.TypedArrayPrototypeGetLength)(src);
} else {
list = [...src];
length = list.length;
}
} else {
if (src == null) {
throw (0, _primordials.NativeTypeError)(_messages.CANNOT_CONVERT_UNDEFINED_OR_NULL_TO_OBJECT);
}
list = (0, _primordials.NativeObject)(src);
length = (0, _spec.ToLength)(list.length);
}
const array = new Constructor(length);
if (opts.length === 0) {
for (let i = 0; i < length; ++i) {
array[i] = list[i];
}
} else {
const mapFunc = opts[0];
const thisArg = opts[1];
for (let i = 0; i < length; ++i) {
array[i] = (0, _primordials.ReflectApply)(mapFunc, thisArg, [list[i], i]);
}
}
return array;
}
static of(...items) {
const Constructor = this;
if (!(0, _primordials.ReflectHas)(Constructor, _brand.brand)) {
throw (0, _primordials.NativeTypeError)(_messages.THIS_CONSTRUCTOR_IS_NOT_A_SUBCLASS_OF_FLOAT16ARRAY);
}
const length = items.length;
if (Constructor === Float16Array) {
const proxy = new Float16Array(length);
const float16bitsArray = getFloat16BitsArray(proxy);
for (let i = 0; i < length; ++i) {
float16bitsArray[i] = (0, _converter.roundToFloat16Bits)(items[i]);
}
return proxy;
}
const array = new Constructor(length);
for (let i = 0; i < length; ++i) {
array[i] = items[i];
}
return array;
}
keys() {
assertFloat16Array(this);
const float16bitsArray = getFloat16BitsArray(this);
return (0, _primordials.TypedArrayPrototypeKeys)(float16bitsArray);
}
values() {
assertFloat16Array(this);
const float16bitsArray = getFloat16BitsArray(this);
return (0, _arrayIterator.wrap)(function* () {
for (const val of (0, _primordials.TypedArrayPrototypeValues)(float16bitsArray)) {
yield (0, _converter.convertToNumber)(val);
}
}());
}
entries() {
assertFloat16Array(this);
const float16bitsArray = getFloat16BitsArray(this);
return (0, _arrayIterator.wrap)(function* () {
for (const [i, val] of (0, _primordials.TypedArrayPrototypeEntries)(float16bitsArray)) {
yield ([i, (0, _converter.convertToNumber)(val)]);
}
}());
}
at(index) {
assertFloat16Array(this);
const float16bitsArray = getFloat16BitsArray(this);
const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
const relativeIndex = (0, _spec.ToIntegerOrInfinity)(index);
const k = relativeIndex >= 0 ? relativeIndex : length + relativeIndex;
if (k < 0 || k >= length) {
return;
}
return (0, _converter.convertToNumber)(float16bitsArray[k]);
}
with(index, value) {
assertFloat16Array(this);
const float16bitsArray = getFloat16BitsArray(this);
const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
const relativeIndex = (0, _spec.ToIntegerOrInfinity)(index);
const k = relativeIndex >= 0 ? relativeIndex : length + relativeIndex;
const number = +value;
if (k < 0 || k >= length) {
throw (0, _primordials.NativeRangeError)(_messages.OFFSET_IS_OUT_OF_BOUNDS);
}
const uint16 = new _primordials.NativeUint16Array((0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetByteOffset)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray));
const cloned = new Float16Array((0, _primordials.TypedArrayPrototypeGetBuffer)((0, _primordials.TypedArrayPrototypeSlice)(uint16)));
const array = getFloat16BitsArray(cloned);
array[k] = (0, _converter.roundToFloat16Bits)(number);
return cloned;
}
map(callback, ...opts) {
assertFloat16Array(this);
const float16bitsArray = getFloat16BitsArray(this);
const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
const thisArg = opts[0];
const Constructor = (0, _spec.SpeciesConstructor)(float16bitsArray, Float16Array);
if (Constructor === Float16Array) {
const proxy = new Float16Array(length);
const array = getFloat16BitsArray(proxy);
for (let i = 0; i < length; ++i) {
const val = (0, _converter.convertToNumber)(float16bitsArray[i]);
array[i] = (0, _converter.roundToFloat16Bits)((0, _primordials.ReflectApply)(callback, thisArg, [val, i, this]));
}
return proxy;
}
const array = new Constructor(length);
assertSpeciesTypedArray(array, length);
for (let i = 0; i < length; ++i) {
const val = (0, _converter.convertToNumber)(float16bitsArray[i]);
array[i] = (0, _primordials.ReflectApply)(callback, thisArg, [val, i, this]);
}
return array;
}
filter(callback, ...opts) {
assertFloat16Array(this);
const float16bitsArray = getFloat16BitsArray(this);
const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
const thisArg = opts[0];
const kept = [];
for (let i = 0; i < length; ++i) {
const val = (0, _converter.convertToNumber)(float16bitsArray[i]);
if ((0, _primordials.ReflectApply)(callback, thisArg, [val, i, this])) {
(0, _primordials.ArrayPrototypePush)(kept, val);
}
}
const Constructor = (0, _spec.SpeciesConstructor)(float16bitsArray, Float16Array);
const array = new Constructor(kept);
assertSpeciesTypedArray(array);
return array;
}
reduce(callback, ...opts) {
assertFloat16Array(this);
const float16bitsArray = getFloat16BitsArray(this);
const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
if (length === 0 && opts.length === 0) {
throw (0, _primordials.NativeTypeError)(_messages.REDUCE_OF_EMPTY_ARRAY_WITH_NO_INITIAL_VALUE);
}
let accumulator, start;
if (opts.length === 0) {
accumulator = (0, _converter.convertToNumber)(float16bitsArray[0]);
start = 1;
} else {
accumulator = opts[0];
start = 0;
}
for (let i = start; i < length; ++i) {
accumulator = callback(accumulator, (0, _converter.convertToNumber)(float16bitsArray[i]), i, this);
}
return accumulator;
}
reduceRight(callback, ...opts) {
assertFloat16Array(this);
const float16bitsArray = getFloat16BitsArray(this);
const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
if (length === 0 && opts.length === 0) {
throw (0, _primordials.NativeTypeError)(_messages.REDUCE_OF_EMPTY_ARRAY_WITH_NO_INITIAL_VALUE);
}
let accumulator, start;
if (opts.length === 0) {
accumulator = (0, _converter.convertToNumber)(float16bitsArray[length - 1]);
start = length - 2;
} else {
accumulator = opts[0];
start = length - 1;
}
for (let i = start; i >= 0; --i) {
accumulator = callback(accumulator, (0, _converter.convertToNumber)(float16bitsArray[i]), i, this);
}
return accumulator;
}
forEach(callback, ...opts) {
assertFloat16Array(this);
const float16bitsArray = getFloat16BitsArray(this);
const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
const thisArg = opts[0];
for (let i = 0; i < length; ++i) {
(0, _primordials.ReflectApply)(callback, thisArg, [(0, _converter.convertToNumber)(float16bitsArray[i]), i, this]);
}
}
find(callback, ...opts) {
assertFloat16Array(this);
const float16bitsArray = getFloat16BitsArray(this);
const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
const thisArg = opts[0];
for (let i = 0; i < length; ++i) {
const value = (0, _converter.convertToNumber)(float16bitsArray[i]);
if ((0, _primordials.ReflectApply)(callback, thisArg, [value, i, this])) {
return value;
}
}
}
findIndex(callback, ...opts) {
assertFloat16Array(this);
const float16bitsArray = getFloat16BitsArray(this);
const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
const thisArg = opts[0];
for (let i = 0; i < length; ++i) {
const value = (0, _converter.convertToNumber)(float16bitsArray[i]);
if ((0, _primordials.ReflectApply)(callback, thisArg, [value, i, this])) {
return i;
}
}
return -1;
}
findLast(callback, ...opts) {
assertFloat16Array(this);
const float16bitsArray = getFloat16BitsArray(this);
const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
const thisArg = opts[0];
for (let i = length - 1; i >= 0; --i) {
const value = (0, _converter.convertToNumber)(float16bitsArray[i]);
if ((0, _primordials.ReflectApply)(callback, thisArg, [value, i, this])) {
return value;
}
}
}
findLastIndex(callback, ...opts) {
assertFloat16Array(this);
const float16bitsArray = getFloat16BitsArray(this);
const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
const thisArg = opts[0];
for (let i = length - 1; i >= 0; --i) {
const value = (0, _converter.convertToNumber)(float16bitsArray[i]);
if ((0, _primordials.ReflectApply)(callback, thisArg, [value, i, this])) {
return i;
}
}
return -1;
}
every(callback, ...opts) {
assertFloat16Array(this);
const float16bitsArray = getFloat16BitsArray(this);
const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
const thisArg = opts[0];
for (let i = 0; i < length; ++i) {
if (!(0, _primordials.ReflectApply)(callback, thisArg, [(0, _converter.convertToNumber)(float16bitsArray[i]), i, this])) {
return false;
}
}
return true;
}
some(callback, ...opts) {
assertFloat16Array(this);
const float16bitsArray = getFloat16BitsArray(this);
const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
const thisArg = opts[0];
for (let i = 0; i < length; ++i) {
if ((0, _primordials.ReflectApply)(callback, thisArg, [(0, _converter.convertToNumber)(float16bitsArray[i]), i, this])) {
return true;
}
}
return false;
}
set(input, ...opts) {
assertFloat16Array(this);
const float16bitsArray = getFloat16BitsArray(this);
const targetOffset = (0, _spec.ToIntegerOrInfinity)(opts[0]);
if (targetOffset < 0) {
throw (0, _primordials.NativeRangeError)(_messages.OFFSET_IS_OUT_OF_BOUNDS);
}
if (input == null) {
throw (0, _primordials.NativeTypeError)(_messages.CANNOT_CONVERT_UNDEFINED_OR_NULL_TO_OBJECT);
}
if ((0, _is.isNativeBigIntTypedArray)(input)) {
throw (0, _primordials.NativeTypeError)(_messages.CANNOT_MIX_BIGINT_AND_OTHER_TYPES);
}
if (isFloat16Array(input)) {
return (0, _primordials.TypedArrayPrototypeSet)(getFloat16BitsArray(this), getFloat16BitsArray(input), targetOffset);
}
if ((0, _is.isNativeTypedArray)(input)) {
const buffer = (0, _primordials.TypedArrayPrototypeGetBuffer)(input);
if ((0, _spec.IsDetachedBuffer)(buffer)) {
throw (0, _primordials.NativeTypeError)(_messages.ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER);
}
}
const targetLength = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
const src = (0, _primordials.NativeObject)(input);
const srcLength = (0, _spec.ToLength)(src.length);
if (targetOffset === Infinity || srcLength + targetOffset > targetLength) {
throw (0, _primordials.NativeRangeError)(_messages.OFFSET_IS_OUT_OF_BOUNDS);
}
for (let i = 0; i < srcLength; ++i) {
float16bitsArray[i + targetOffset] = (0, _converter.roundToFloat16Bits)(src[i]);
}
}
reverse() {
assertFloat16Array(this);
const float16bitsArray = getFloat16BitsArray(this);
(0, _primordials.TypedArrayPrototypeReverse)(float16bitsArray);
return this;
}
toReversed() {
assertFloat16Array(this);
const float16bitsArray = getFloat16BitsArray(this);
const uint16 = new _primordials.NativeUint16Array((0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetByteOffset)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray));
const cloned = new Float16Array((0, _primordials.TypedArrayPrototypeGetBuffer)((0, _primordials.TypedArrayPrototypeSlice)(uint16)));
const clonedFloat16bitsArray = getFloat16BitsArray(cloned);
(0, _primordials.TypedArrayPrototypeReverse)(clonedFloat16bitsArray);
return cloned;
}
fill(value, ...opts) {
assertFloat16Array(this);
const float16bitsArray = getFloat16BitsArray(this);
(0, _primordials.TypedArrayPrototypeFill)(float16bitsArray, (0, _converter.roundToFloat16Bits)(value), ...(0, _arrayIterator.safeIfNeeded)(opts));
return this;
}
copyWithin(target, start, ...opts) {
assertFloat16Array(this);
const float16bitsArray = getFloat16BitsArray(this);
(0, _primordials.TypedArrayPrototypeCopyWithin)(float16bitsArray, target, start, ...(0, _arrayIterator.safeIfNeeded)(opts));
return this;
}
sort(compareFn) {
assertFloat16Array(this);
const float16bitsArray = getFloat16BitsArray(this);
const sortCompare = compareFn !== undefined ? compareFn : _spec.defaultCompare;
(0, _primordials.TypedArrayPrototypeSort)(float16bitsArray, (x, y) => {
return sortCompare((0, _converter.convertToNumber)(x), (0, _converter.convertToNumber)(y));
});
return this;
}
toSorted(compareFn) {
assertFloat16Array(this);
const float16bitsArray = getFloat16BitsArray(this);
if (compareFn !== undefined && typeof compareFn !== "function") {
throw new _primordials.NativeTypeError(_messages.THE_COMPARISON_FUNCTION_MUST_BE_EITHER_A_FUNCTION_OR_UNDEFINED);
}
const sortCompare = compareFn !== undefined ? compareFn : _spec.defaultCompare;
const uint16 = new _primordials.NativeUint16Array((0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetByteOffset)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray));
const cloned = new Float16Array((0, _primordials.TypedArrayPrototypeGetBuffer)((0, _primordials.TypedArrayPrototypeSlice)(uint16)));
const clonedFloat16bitsArray = getFloat16BitsArray(cloned);
(0, _primordials.TypedArrayPrototypeSort)(clonedFloat16bitsArray, (x, y) => {
return sortCompare((0, _converter.convertToNumber)(x), (0, _converter.convertToNumber)(y));
});
return cloned;
}
slice(start, end) {
assertFloat16Array(this);
const float16bitsArray = getFloat16BitsArray(this);
const Constructor = (0, _spec.SpeciesConstructor)(float16bitsArray, Float16Array);
if (Constructor === Float16Array) {
const uint16 = new _primordials.NativeUint16Array((0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetByteOffset)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray));
return new Float16Array((0, _primordials.TypedArrayPrototypeGetBuffer)((0, _primordials.TypedArrayPrototypeSlice)(uint16, start, end)));
}
const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
const relativeStart = (0, _spec.ToIntegerOrInfinity)(start);
const relativeEnd = end === undefined ? length : (0, _spec.ToIntegerOrInfinity)(end);
let k;
if (relativeStart === -Infinity) {
k = 0;
} else if (relativeStart < 0) {
k = length + relativeStart > 0 ? length + relativeStart : 0;
} else {
k = length < relativeStart ? length : relativeStart;
}
let final;
if (relativeEnd === -Infinity) {
final = 0;
} else if (relativeEnd < 0) {
final = length + relativeEnd > 0 ? length + relativeEnd : 0;
} else {
final = length < relativeEnd ? length : relativeEnd;
}
const count = final - k > 0 ? final - k : 0;
const array = new Constructor(count);
assertSpeciesTypedArray(array, count);
if (count === 0) {
return array;
}
const buffer = (0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray);
if ((0, _spec.IsDetachedBuffer)(buffer)) {
throw (0, _primordials.NativeTypeError)(_messages.ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER);
}
let n = 0;
while (k < final) {
array[n] = (0, _converter.convertToNumber)(float16bitsArray[k]);
++k;
++n;
}
return array;
}
subarray(begin, end) {
assertFloat16Array(this);
const float16bitsArray = getFloat16BitsArray(this);
const Constructor = (0, _spec.SpeciesConstructor)(float16bitsArray, Float16Array);
const uint16 = new _primordials.NativeUint16Array((0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetByteOffset)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray));
const uint16Subarray = (0, _primordials.TypedArrayPrototypeSubarray)(uint16, begin, end);
const array = new Constructor((0, _primordials.TypedArrayPrototypeGetBuffer)(uint16Subarray), (0, _primordials.TypedArrayPrototypeGetByteOffset)(uint16Subarray), (0, _primordials.TypedArrayPrototypeGetLength)(uint16Subarray));
assertSpeciesTypedArray(array);
return array;
}
indexOf(element, ...opts) {
assertFloat16Array(this);
const float16bitsArray = getFloat16BitsArray(this);
const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
let from = (0, _spec.ToIntegerOrInfinity)(opts[0]);
if (from === Infinity) {
return -1;
}
if (from < 0) {
from += length;
if (from < 0) {
from = 0;
}
}
for (let i = from; i < length; ++i) {
if ((0, _primordials.ObjectHasOwn)(float16bitsArray, i) && (0, _converter.convertToNumber)(float16bitsArray[i]) === element) {
return i;
}
}
return -1;
}
lastIndexOf(element, ...opts) {
assertFloat16Array(this);
const float16bitsArray = getFloat16BitsArray(this);
const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
let from = opts.length >= 1 ? (0, _spec.ToIntegerOrInfinity)(opts[0]) : length - 1;
if (from === -Infinity) {
return -1;
}
if (from >= 0) {
from = from < length - 1 ? from : length - 1;
} else {
from += length;
}
for (let i = from; i >= 0; --i) {
if ((0, _primordials.ObjectHasOwn)(float16bitsArray, i) && (0, _converter.convertToNumber)(float16bitsArray[i]) === element) {
return i;
}
}
return -1;
}
includes(element, ...opts) {
assertFloat16Array(this);
const float16bitsArray = getFloat16BitsArray(this);
const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
let from = (0, _spec.ToIntegerOrInfinity)(opts[0]);
if (from === Infinity) {
return false;
}
if (from < 0) {
from += length;
if (from < 0) {
from = 0;
}
}
const isNaN = (0, _primordials.NumberIsNaN)(element);
for (let i = from; i < length; ++i) {
const value = (0, _converter.convertToNumber)(float16bitsArray[i]);
if (isNaN && (0, _primordials.NumberIsNaN)(value)) {
return true;
}
if (value === element) {
return true;
}
}
return false;
}
join(separator) {
assertFloat16Array(this);
const float16bitsArray = getFloat16BitsArray(this);
const array = copyToArray(float16bitsArray);
return (0, _primordials.ArrayPrototypeJoin)(array, separator);
}
toLocaleString(...opts) {
assertFloat16Array(this);
const float16bitsArray = getFloat16BitsArray(this);
const array = copyToArray(float16bitsArray);
return (0, _primordials.ArrayPrototypeToLocaleString)(array, ...(0, _arrayIterator.safeIfNeeded)(opts));
}
get [_primordials.SymbolToStringTag]() {
if (isFloat16Array(this)) {
return "Float16Array";
}
}
}
exports.Float16Array = Float16Array;
(0, _primordials.ObjectDefineProperty)(Float16Array, "BYTES_PER_ELEMENT", {
value: BYTES_PER_ELEMENT
});
(0, _primordials.ObjectDefineProperty)(Float16Array, _brand.brand, {});
(0, _primordials.ReflectSetPrototypeOf)(Float16Array, _primordials.TypedArray);
const Float16ArrayPrototype = Float16Array.prototype;
(0, _primordials.ObjectDefineProperty)(Float16ArrayPrototype, "BYTES_PER_ELEMENT", {
value: BYTES_PER_ELEMENT
});
(0, _primordials.ObjectDefineProperty)(Float16ArrayPrototype, _primordials.SymbolIterator, {
value: Float16ArrayPrototype.values,
writable: true,
configurable: true
});
(0, _primordials.ReflectSetPrototypeOf)(Float16ArrayPrototype, _primordials.TypedArrayPrototype);
-52
View File
@@ -1,52 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.safeIfNeeded = safeIfNeeded;
exports.wrap = wrap;
var _primordials = require("./primordials.cjs");
const arrayIterators = new _primordials.NativeWeakMap();
const SafeIteratorPrototype = (0, _primordials.ObjectCreate)(null, {
next: {
value: function next() {
const arrayIterator = (0, _primordials.WeakMapPrototypeGet)(arrayIterators, this);
return (0, _primordials.ArrayIteratorPrototypeNext)(arrayIterator);
}
},
[_primordials.SymbolIterator]: {
value: function values() {
return this;
}
}
});
function safeIfNeeded(array) {
if (array[_primordials.SymbolIterator] === _primordials.NativeArrayPrototypeSymbolIterator && _primordials.ArrayIteratorPrototype.next === _primordials.ArrayIteratorPrototypeNext) {
return array;
}
const safe = (0, _primordials.ObjectCreate)(SafeIteratorPrototype);
(0, _primordials.WeakMapPrototypeSet)(arrayIterators, safe, (0, _primordials.ArrayPrototypeSymbolIterator)(array));
return safe;
}
const generators = new _primordials.NativeWeakMap();
const DummyArrayIteratorPrototype = (0, _primordials.ObjectCreate)(_primordials.IteratorPrototype, {
next: {
value: function next() {
const generator = (0, _primordials.WeakMapPrototypeGet)(generators, this);
return (0, _primordials.GeneratorPrototypeNext)(generator);
},
writable: true,
configurable: true
}
});
for (const key of (0, _primordials.ReflectOwnKeys)(_primordials.ArrayIteratorPrototype)) {
if (key === "next") {
continue;
}
(0, _primordials.ObjectDefineProperty)(DummyArrayIteratorPrototype, key, (0, _primordials.ReflectGetOwnPropertyDescriptor)(_primordials.ArrayIteratorPrototype, key));
}
function wrap(generator) {
const dummy = (0, _primordials.ObjectCreate)(DummyArrayIteratorPrototype);
(0, _primordials.WeakMapPrototypeSet)(generators, dummy, generator);
return dummy;
}
-27
View File
@@ -1,27 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.hasFloat16ArrayBrand = hasFloat16ArrayBrand;
var _is = require("./is.cjs");
var _messages = require("./messages.cjs");
var _primordials = require("./primordials.cjs");
const brand = exports.brand = (0, _primordials.SymbolFor)("__Float16Array__");
function hasFloat16ArrayBrand(target) {
if (!(0, _is.isObjectLike)(target)) {
return false;
}
const prototype = (0, _primordials.ReflectGetPrototypeOf)(target);
if (!(0, _is.isObjectLike)(prototype)) {
return false;
}
const constructor = prototype.constructor;
if (constructor === undefined) {
return false;
}
if (!(0, _is.isObject)(constructor)) {
throw (0, _primordials.NativeTypeError)(_messages.THE_CONSTRUCTOR_PROPERTY_VALUE_IS_NOT_AN_OBJECT);
}
return (0, _primordials.ReflectHas)(constructor, brand);
}
-111
View File
@@ -1,111 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.convertToNumber = convertToNumber;
exports.roundToFloat16 = roundToFloat16;
exports.roundToFloat16Bits = roundToFloat16Bits;
var _primordials = require("./primordials.cjs");
const INVERSE_OF_EPSILON = 1 / _primordials.EPSILON;
function roundTiesToEven(num) {
return num + INVERSE_OF_EPSILON - INVERSE_OF_EPSILON;
}
const FLOAT16_MIN_VALUE = 6.103515625e-05;
const FLOAT16_MAX_VALUE = 65504;
const FLOAT16_EPSILON = 0.0009765625;
const FLOAT16_EPSILON_MULTIPLIED_BY_FLOAT16_MIN_VALUE = FLOAT16_EPSILON * FLOAT16_MIN_VALUE;
const FLOAT16_EPSILON_DEVIDED_BY_EPSILON = FLOAT16_EPSILON * INVERSE_OF_EPSILON;
function roundToFloat16(num) {
const number = +num;
if (!(0, _primordials.NumberIsFinite)(number) || number === 0) {
return number;
}
const sign = number > 0 ? 1 : -1;
const absolute = (0, _primordials.MathAbs)(number);
if (absolute < FLOAT16_MIN_VALUE) {
return sign * roundTiesToEven(absolute / FLOAT16_EPSILON_MULTIPLIED_BY_FLOAT16_MIN_VALUE) * FLOAT16_EPSILON_MULTIPLIED_BY_FLOAT16_MIN_VALUE;
}
const temp = (1 + FLOAT16_EPSILON_DEVIDED_BY_EPSILON) * absolute;
const result = temp - (temp - absolute);
if (result > FLOAT16_MAX_VALUE || (0, _primordials.NumberIsNaN)(result)) {
return sign * Infinity;
}
return sign * result;
}
const buffer = new _primordials.NativeArrayBuffer(4);
const floatView = new _primordials.NativeFloat32Array(buffer);
const uint32View = new _primordials.NativeUint32Array(buffer);
const baseTable = new _primordials.NativeUint16Array(512);
const shiftTable = new _primordials.NativeUint8Array(512);
for (let i = 0; i < 256; ++i) {
const e = i - 127;
if (e < -24) {
baseTable[i] = 0x0000;
baseTable[i | 0x100] = 0x8000;
shiftTable[i] = 24;
shiftTable[i | 0x100] = 24;
} else if (e < -14) {
baseTable[i] = 0x0400 >> -e - 14;
baseTable[i | 0x100] = 0x0400 >> -e - 14 | 0x8000;
shiftTable[i] = -e - 1;
shiftTable[i | 0x100] = -e - 1;
} else if (e <= 15) {
baseTable[i] = e + 15 << 10;
baseTable[i | 0x100] = e + 15 << 10 | 0x8000;
shiftTable[i] = 13;
shiftTable[i | 0x100] = 13;
} else if (e < 128) {
baseTable[i] = 0x7c00;
baseTable[i | 0x100] = 0xfc00;
shiftTable[i] = 24;
shiftTable[i | 0x100] = 24;
} else {
baseTable[i] = 0x7c00;
baseTable[i | 0x100] = 0xfc00;
shiftTable[i] = 13;
shiftTable[i | 0x100] = 13;
}
}
function roundToFloat16Bits(num) {
floatView[0] = roundToFloat16(num);
const f = uint32View[0];
const e = f >> 23 & 0x1ff;
return baseTable[e] + ((f & 0x007fffff) >> shiftTable[e]);
}
const mantissaTable = new _primordials.NativeUint32Array(2048);
for (let i = 1; i < 1024; ++i) {
let m = i << 13;
let e = 0;
while ((m & 0x00800000) === 0) {
m <<= 1;
e -= 0x00800000;
}
m &= ~0x00800000;
e += 0x38800000;
mantissaTable[i] = m | e;
}
for (let i = 1024; i < 2048; ++i) {
mantissaTable[i] = 0x38000000 + (i - 1024 << 13);
}
const exponentTable = new _primordials.NativeUint32Array(64);
for (let i = 1; i < 31; ++i) {
exponentTable[i] = i << 23;
}
exponentTable[31] = 0x47800000;
exponentTable[32] = 0x80000000;
for (let i = 33; i < 63; ++i) {
exponentTable[i] = 0x80000000 + (i - 32 << 23);
}
exponentTable[63] = 0xc7800000;
const offsetTable = new _primordials.NativeUint16Array(64);
for (let i = 1; i < 64; ++i) {
if (i !== 32) {
offsetTable[i] = 1024;
}
}
function convertToNumber(float16bits) {
const i = float16bits >> 10;
uint32View[0] = mantissaTable[offsetTable[i] + (float16bits & 0x3ff)] + exponentTable[i];
return floatView[0];
}
-78
View File
@@ -1,78 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isAnyArrayBuffer = isAnyArrayBuffer;
exports.isCanonicalIntegerIndexString = isCanonicalIntegerIndexString;
exports.isNativeBigIntTypedArray = isNativeBigIntTypedArray;
exports.isNativeTypedArray = isNativeTypedArray;
exports.isObject = isObject;
exports.isObjectLike = isObjectLike;
exports.isOrdinaryArray = isOrdinaryArray;
exports.isOrdinaryNativeTypedArray = isOrdinaryNativeTypedArray;
exports.isSharedArrayBuffer = isSharedArrayBuffer;
var _primordials = require("./primordials.cjs");
function isObject(value) {
return value !== null && typeof value === "object" || typeof value === "function";
}
function isObjectLike(value) {
return value !== null && typeof value === "object";
}
function isNativeTypedArray(value) {
return (0, _primordials.TypedArrayPrototypeGetSymbolToStringTag)(value) !== undefined;
}
function isNativeBigIntTypedArray(value) {
const typedArrayName = (0, _primordials.TypedArrayPrototypeGetSymbolToStringTag)(value);
return typedArrayName === "BigInt64Array" || typedArrayName === "BigUint64Array";
}
function isArrayBuffer(value) {
try {
if ((0, _primordials.ArrayIsArray)(value)) {
return false;
}
(0, _primordials.ArrayBufferPrototypeGetByteLength)(value);
return true;
} catch (e) {
return false;
}
}
function isSharedArrayBuffer(value) {
if (_primordials.NativeSharedArrayBuffer === null) {
return false;
}
try {
(0, _primordials.SharedArrayBufferPrototypeGetByteLength)(value);
return true;
} catch (e) {
return false;
}
}
function isAnyArrayBuffer(value) {
return isArrayBuffer(value) || isSharedArrayBuffer(value);
}
function isOrdinaryArray(value) {
if (!(0, _primordials.ArrayIsArray)(value)) {
return false;
}
return value[_primordials.SymbolIterator] === _primordials.NativeArrayPrototypeSymbolIterator && _primordials.ArrayIteratorPrototype.next === _primordials.ArrayIteratorPrototypeNext;
}
function isOrdinaryNativeTypedArray(value) {
if (!isNativeTypedArray(value)) {
return false;
}
return value[_primordials.SymbolIterator] === _primordials.NativeTypedArrayPrototypeSymbolIterator && _primordials.ArrayIteratorPrototype.next === _primordials.ArrayIteratorPrototypeNext;
}
function isCanonicalIntegerIndexString(value) {
if (typeof value !== "string") {
return false;
}
const number = +value;
if (value !== number + "") {
return false;
}
if (!(0, _primordials.NumberIsFinite)(number)) {
return false;
}
return number === (0, _primordials.MathTrunc)(number);
}
-18
View File
@@ -1,18 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
const THIS_IS_NOT_AN_OBJECT = exports.THIS_IS_NOT_AN_OBJECT = "This is not an object";
const THIS_IS_NOT_A_FLOAT16ARRAY_OBJECT = exports.THIS_IS_NOT_A_FLOAT16ARRAY_OBJECT = "This is not a Float16Array object";
const THIS_CONSTRUCTOR_IS_NOT_A_SUBCLASS_OF_FLOAT16ARRAY = exports.THIS_CONSTRUCTOR_IS_NOT_A_SUBCLASS_OF_FLOAT16ARRAY = "This constructor is not a subclass of Float16Array";
const THE_CONSTRUCTOR_PROPERTY_VALUE_IS_NOT_AN_OBJECT = exports.THE_CONSTRUCTOR_PROPERTY_VALUE_IS_NOT_AN_OBJECT = "The constructor property value is not an object";
const SPECIES_CONSTRUCTOR_DIDNT_RETURN_TYPEDARRAY_OBJECT = exports.SPECIES_CONSTRUCTOR_DIDNT_RETURN_TYPEDARRAY_OBJECT = "Species constructor didn't return TypedArray object";
const DERIVED_CONSTRUCTOR_CREATED_TYPEDARRAY_OBJECT_WHICH_WAS_TOO_SMALL_LENGTH = exports.DERIVED_CONSTRUCTOR_CREATED_TYPEDARRAY_OBJECT_WHICH_WAS_TOO_SMALL_LENGTH = "Derived constructor created TypedArray object which was too small length";
const ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER = exports.ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER = "Attempting to access detached ArrayBuffer";
const CANNOT_CONVERT_UNDEFINED_OR_NULL_TO_OBJECT = exports.CANNOT_CONVERT_UNDEFINED_OR_NULL_TO_OBJECT = "Cannot convert undefined or null to object";
const CANNOT_MIX_BIGINT_AND_OTHER_TYPES = exports.CANNOT_MIX_BIGINT_AND_OTHER_TYPES = "Cannot mix BigInt and other types, use explicit conversions";
const ITERATOR_PROPERTY_IS_NOT_CALLABLE = exports.ITERATOR_PROPERTY_IS_NOT_CALLABLE = "@@iterator property is not callable";
const REDUCE_OF_EMPTY_ARRAY_WITH_NO_INITIAL_VALUE = exports.REDUCE_OF_EMPTY_ARRAY_WITH_NO_INITIAL_VALUE = "Reduce of empty array with no initial value";
const THE_COMPARISON_FUNCTION_MUST_BE_EITHER_A_FUNCTION_OR_UNDEFINED = exports.THE_COMPARISON_FUNCTION_MUST_BE_EITHER_A_FUNCTION_OR_UNDEFINED = "The comparison function must be either a function or undefined";
const OFFSET_IS_OUT_OF_BOUNDS = exports.OFFSET_IS_OUT_OF_BOUNDS = "Offset is out of bounds";
-150
View File
@@ -1,150 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _messages = require("./messages.cjs");
function uncurryThis(target) {
return (thisArg, ...args) => {
return ReflectApply(target, thisArg, args);
};
}
function uncurryThisGetter(target, key) {
return uncurryThis(ReflectGetOwnPropertyDescriptor(target, key).get);
}
const {
apply: ReflectApply,
construct: ReflectConstruct,
defineProperty: ReflectDefineProperty,
get: ReflectGet,
getOwnPropertyDescriptor: ReflectGetOwnPropertyDescriptor,
getPrototypeOf: ReflectGetPrototypeOf,
has: ReflectHas,
ownKeys: ReflectOwnKeys,
set: ReflectSet,
setPrototypeOf: ReflectSetPrototypeOf
} = Reflect;
exports.ReflectSetPrototypeOf = ReflectSetPrototypeOf;
exports.ReflectSet = ReflectSet;
exports.ReflectOwnKeys = ReflectOwnKeys;
exports.ReflectHas = ReflectHas;
exports.ReflectGetPrototypeOf = ReflectGetPrototypeOf;
exports.ReflectGetOwnPropertyDescriptor = ReflectGetOwnPropertyDescriptor;
exports.ReflectGet = ReflectGet;
exports.ReflectDefineProperty = ReflectDefineProperty;
exports.ReflectConstruct = ReflectConstruct;
exports.ReflectApply = ReflectApply;
const NativeProxy = exports.NativeProxy = Proxy;
const {
EPSILON,
MAX_SAFE_INTEGER,
isFinite: NumberIsFinite,
isNaN: NumberIsNaN
} = Number;
exports.NumberIsNaN = NumberIsNaN;
exports.NumberIsFinite = NumberIsFinite;
exports.MAX_SAFE_INTEGER = MAX_SAFE_INTEGER;
exports.EPSILON = EPSILON;
const {
iterator: SymbolIterator,
species: SymbolSpecies,
toStringTag: SymbolToStringTag,
for: SymbolFor
} = Symbol;
exports.SymbolFor = SymbolFor;
exports.SymbolToStringTag = SymbolToStringTag;
exports.SymbolSpecies = SymbolSpecies;
exports.SymbolIterator = SymbolIterator;
const NativeObject = exports.NativeObject = Object;
const {
create: ObjectCreate,
defineProperty: ObjectDefineProperty,
freeze: ObjectFreeze,
is: ObjectIs
} = NativeObject;
exports.ObjectIs = ObjectIs;
exports.ObjectFreeze = ObjectFreeze;
exports.ObjectDefineProperty = ObjectDefineProperty;
exports.ObjectCreate = ObjectCreate;
const ObjectPrototype = NativeObject.prototype;
const ObjectPrototype__lookupGetter__ = exports.ObjectPrototype__lookupGetter__ = ObjectPrototype.__lookupGetter__ ? uncurryThis(ObjectPrototype.__lookupGetter__) : (object, key) => {
if (object == null) {
throw NativeTypeError(_messages.CANNOT_CONVERT_UNDEFINED_OR_NULL_TO_OBJECT);
}
let target = NativeObject(object);
do {
const descriptor = ReflectGetOwnPropertyDescriptor(target, key);
if (descriptor !== undefined) {
if (ObjectHasOwn(descriptor, "get")) {
return descriptor.get;
}
return;
}
} while ((target = ReflectGetPrototypeOf(target)) !== null);
};
const ObjectHasOwn = exports.ObjectHasOwn = NativeObject.hasOwn || uncurryThis(ObjectPrototype.hasOwnProperty);
const NativeArray = Array;
const ArrayIsArray = exports.ArrayIsArray = NativeArray.isArray;
const ArrayPrototype = NativeArray.prototype;
const ArrayPrototypeJoin = exports.ArrayPrototypeJoin = uncurryThis(ArrayPrototype.join);
const ArrayPrototypePush = exports.ArrayPrototypePush = uncurryThis(ArrayPrototype.push);
const ArrayPrototypeToLocaleString = exports.ArrayPrototypeToLocaleString = uncurryThis(ArrayPrototype.toLocaleString);
const NativeArrayPrototypeSymbolIterator = exports.NativeArrayPrototypeSymbolIterator = ArrayPrototype[SymbolIterator];
const ArrayPrototypeSymbolIterator = exports.ArrayPrototypeSymbolIterator = uncurryThis(NativeArrayPrototypeSymbolIterator);
const {
abs: MathAbs,
trunc: MathTrunc
} = Math;
exports.MathTrunc = MathTrunc;
exports.MathAbs = MathAbs;
const NativeArrayBuffer = exports.NativeArrayBuffer = ArrayBuffer;
const ArrayBufferIsView = exports.ArrayBufferIsView = NativeArrayBuffer.isView;
const ArrayBufferPrototype = NativeArrayBuffer.prototype;
const ArrayBufferPrototypeSlice = exports.ArrayBufferPrototypeSlice = uncurryThis(ArrayBufferPrototype.slice);
const ArrayBufferPrototypeGetByteLength = exports.ArrayBufferPrototypeGetByteLength = uncurryThisGetter(ArrayBufferPrototype, "byteLength");
const NativeSharedArrayBuffer = exports.NativeSharedArrayBuffer = typeof SharedArrayBuffer !== "undefined" ? SharedArrayBuffer : null;
const SharedArrayBufferPrototypeGetByteLength = exports.SharedArrayBufferPrototypeGetByteLength = NativeSharedArrayBuffer && uncurryThisGetter(NativeSharedArrayBuffer.prototype, "byteLength");
const TypedArray = exports.TypedArray = ReflectGetPrototypeOf(Uint8Array);
const TypedArrayFrom = TypedArray.from;
const TypedArrayPrototype = exports.TypedArrayPrototype = TypedArray.prototype;
const NativeTypedArrayPrototypeSymbolIterator = exports.NativeTypedArrayPrototypeSymbolIterator = TypedArrayPrototype[SymbolIterator];
const TypedArrayPrototypeKeys = exports.TypedArrayPrototypeKeys = uncurryThis(TypedArrayPrototype.keys);
const TypedArrayPrototypeValues = exports.TypedArrayPrototypeValues = uncurryThis(TypedArrayPrototype.values);
const TypedArrayPrototypeEntries = exports.TypedArrayPrototypeEntries = uncurryThis(TypedArrayPrototype.entries);
const TypedArrayPrototypeSet = exports.TypedArrayPrototypeSet = uncurryThis(TypedArrayPrototype.set);
const TypedArrayPrototypeReverse = exports.TypedArrayPrototypeReverse = uncurryThis(TypedArrayPrototype.reverse);
const TypedArrayPrototypeFill = exports.TypedArrayPrototypeFill = uncurryThis(TypedArrayPrototype.fill);
const TypedArrayPrototypeCopyWithin = exports.TypedArrayPrototypeCopyWithin = uncurryThis(TypedArrayPrototype.copyWithin);
const TypedArrayPrototypeSort = exports.TypedArrayPrototypeSort = uncurryThis(TypedArrayPrototype.sort);
const TypedArrayPrototypeSlice = exports.TypedArrayPrototypeSlice = uncurryThis(TypedArrayPrototype.slice);
const TypedArrayPrototypeSubarray = exports.TypedArrayPrototypeSubarray = uncurryThis(TypedArrayPrototype.subarray);
const TypedArrayPrototypeGetBuffer = exports.TypedArrayPrototypeGetBuffer = uncurryThisGetter(TypedArrayPrototype, "buffer");
const TypedArrayPrototypeGetByteOffset = exports.TypedArrayPrototypeGetByteOffset = uncurryThisGetter(TypedArrayPrototype, "byteOffset");
const TypedArrayPrototypeGetLength = exports.TypedArrayPrototypeGetLength = uncurryThisGetter(TypedArrayPrototype, "length");
const TypedArrayPrototypeGetSymbolToStringTag = exports.TypedArrayPrototypeGetSymbolToStringTag = uncurryThisGetter(TypedArrayPrototype, SymbolToStringTag);
const NativeUint8Array = exports.NativeUint8Array = Uint8Array;
const NativeUint16Array = exports.NativeUint16Array = Uint16Array;
const Uint16ArrayFrom = (...args) => {
return ReflectApply(TypedArrayFrom, NativeUint16Array, args);
};
exports.Uint16ArrayFrom = Uint16ArrayFrom;
const NativeUint32Array = exports.NativeUint32Array = Uint32Array;
const NativeFloat32Array = exports.NativeFloat32Array = Float32Array;
const ArrayIteratorPrototype = exports.ArrayIteratorPrototype = ReflectGetPrototypeOf([][SymbolIterator]());
const ArrayIteratorPrototypeNext = exports.ArrayIteratorPrototypeNext = uncurryThis(ArrayIteratorPrototype.next);
const GeneratorPrototypeNext = exports.GeneratorPrototypeNext = uncurryThis(function* () {}().next);
const IteratorPrototype = exports.IteratorPrototype = ReflectGetPrototypeOf(ArrayIteratorPrototype);
const DataViewPrototype = DataView.prototype;
const DataViewPrototypeGetUint16 = exports.DataViewPrototypeGetUint16 = uncurryThis(DataViewPrototype.getUint16);
const DataViewPrototypeSetUint16 = exports.DataViewPrototypeSetUint16 = uncurryThis(DataViewPrototype.setUint16);
const NativeTypeError = exports.NativeTypeError = TypeError;
const NativeRangeError = exports.NativeRangeError = RangeError;
const NativeWeakSet = exports.NativeWeakSet = WeakSet;
const WeakSetPrototype = NativeWeakSet.prototype;
const WeakSetPrototypeAdd = exports.WeakSetPrototypeAdd = uncurryThis(WeakSetPrototype.add);
const WeakSetPrototypeHas = exports.WeakSetPrototypeHas = uncurryThis(WeakSetPrototype.has);
const NativeWeakMap = exports.NativeWeakMap = WeakMap;
const WeakMapPrototype = NativeWeakMap.prototype;
const WeakMapPrototypeGet = exports.WeakMapPrototypeGet = uncurryThis(WeakMapPrototype.get);
const WeakMapPrototypeHas = exports.WeakMapPrototypeHas = uncurryThis(WeakMapPrototype.has);
const WeakMapPrototypeSet = exports.WeakMapPrototypeSet = uncurryThis(WeakMapPrototype.set);
-84
View File
@@ -1,84 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.IsDetachedBuffer = IsDetachedBuffer;
exports.SpeciesConstructor = SpeciesConstructor;
exports.ToIntegerOrInfinity = ToIntegerOrInfinity;
exports.ToLength = ToLength;
exports.defaultCompare = defaultCompare;
var _is = require("./is.cjs");
var _messages = require("./messages.cjs");
var _primordials = require("./primordials.cjs");
function ToIntegerOrInfinity(target) {
const number = +target;
if ((0, _primordials.NumberIsNaN)(number) || number === 0) {
return 0;
}
return (0, _primordials.MathTrunc)(number);
}
function ToLength(target) {
const length = ToIntegerOrInfinity(target);
if (length < 0) {
return 0;
}
return length < _primordials.MAX_SAFE_INTEGER ? length : _primordials.MAX_SAFE_INTEGER;
}
function SpeciesConstructor(target, defaultConstructor) {
if (!(0, _is.isObject)(target)) {
throw (0, _primordials.NativeTypeError)(_messages.THIS_IS_NOT_AN_OBJECT);
}
const constructor = target.constructor;
if (constructor === undefined) {
return defaultConstructor;
}
if (!(0, _is.isObject)(constructor)) {
throw (0, _primordials.NativeTypeError)(_messages.THE_CONSTRUCTOR_PROPERTY_VALUE_IS_NOT_AN_OBJECT);
}
const species = constructor[_primordials.SymbolSpecies];
if (species == null) {
return defaultConstructor;
}
return species;
}
function IsDetachedBuffer(buffer) {
if ((0, _is.isSharedArrayBuffer)(buffer)) {
return false;
}
try {
(0, _primordials.ArrayBufferPrototypeSlice)(buffer, 0, 0);
return false;
} catch (e) {}
return true;
}
function defaultCompare(x, y) {
const isXNaN = (0, _primordials.NumberIsNaN)(x);
const isYNaN = (0, _primordials.NumberIsNaN)(y);
if (isXNaN && isYNaN) {
return 0;
}
if (isXNaN) {
return 1;
}
if (isYNaN) {
return -1;
}
if (x < y) {
return -1;
}
if (x > y) {
return 1;
}
if (x === 0 && y === 0) {
const isXPlusZero = (0, _primordials.ObjectIs)(x, 0);
const isYPlusZero = (0, _primordials.ObjectIs)(y, 0);
if (!isXPlusZero && isYPlusZero) {
return -1;
}
if (isXPlusZero && !isYPlusZero) {
return 1;
}
}
return 0;
}
-10
View File
@@ -1,10 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.f16round = f16round;
var _converter = require("./_util/converter.cjs");
function f16round(x) {
return (0, _converter.roundToFloat16)(x);
}
-16
View File
@@ -1,16 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _Float16Array = require("./Float16Array.cjs");
exports.Float16Array = _Float16Array.Float16Array;
exports.isFloat16Array = _Float16Array.isFloat16Array;
var _isTypedArray = require("./isTypedArray.cjs");
exports.isTypedArray = _isTypedArray.isTypedArray;
var _DataView = require("./DataView.cjs");
exports.getFloat16 = _DataView.getFloat16;
exports.setFloat16 = _DataView.setFloat16;
var _f16round = require("./f16round.cjs");
exports.f16round = _f16round.f16round;
exports.hfround = _f16round.f16round;
-11
View File
@@ -1,11 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isTypedArray = isTypedArray;
var _Float16Array = require("./Float16Array.cjs");
var _is = require("./_util/is.cjs");
function isTypedArray(target) {
return (0, _is.isNativeTypedArray)(target) || (0, _Float16Array.isFloat16Array)(target);
}
-115
View File
@@ -1,115 +0,0 @@
{
"name": "@petamoriken/float16",
"version": "3.9.3",
"description": "IEEE 754 half-precision floating-point for JavaScript",
"keywords": [
"float16",
"binary16",
"FP16",
"half-precision",
"ieee754",
"Float16Array",
"TypedArray",
"DataView",
"getFloat16",
"setFloat16",
"f16round",
"ponyfill",
"shim"
],
"homepage": "https://github.com/petamoriken/float16",
"bugs": {
"url": "https://github.com/petamoriken/float16/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/petamoriken/float16.git"
},
"license": "MIT",
"author": "Kenta Moriuchi <moriken@kimamass.com> (https://moriken.dev)",
"sideEffects": false,
"exports": {
".": {
"require": "./lib/index.cjs",
"import": "./src/index.mjs",
"types": "./index.v5.7.d.ts"
},
"./inspect": {
"require": "./inspect/node.cjs",
"import": "./inspect/node.mjs"
}
},
"main": "./lib/index.cjs",
"browser": "./browser/float16.js",
"module": "./src/index.mjs",
"types": "./index.d.ts",
"typesVersions": {
">=5.7": {
"index.d.ts": [
"index.v5.7.d.ts"
]
},
">=5.6": {
"index.d.ts": [
"index.v5.6.d.ts"
]
}
},
"files": [
"src",
"lib",
"browser",
"inspect/node.mjs",
"inspect/node.cjs",
"index.d.ts",
"index.v5.6.d.ts",
"index.v5.7.d.ts"
],
"scripts": {
"build": "concurrently \"yarn:build:*\"",
"build:browser": "rollup -c",
"build:lib": "babel src -d lib --out-file-extension .cjs",
"clean": "rm -rf lib browser docs coverage .nyc_output",
"coverage": "nyc --reporter=lcov mocha test/*.js",
"docs": "mkdir -p docs && cp README.md docs/index.md && yarn run docs:test",
"docs:test": "mkdir -p docs/test && concurrently \"yarn:docs:test:*\"",
"docs:test:build": "cp test/*.js docs/test && tools/power",
"docs:test:copy": "cp browser/float16.js docs/test/float16.js && cp test/browser/*.html docs/test",
"docs:test:dependencies": "cp node_modules/mocha/mocha.js node_modules/mocha/mocha.css node_modules/power-assert/build/power-assert.js docs/test",
"lint": "concurrently \"yarn:lint:*\"",
"lint:eslint": "eslint src/**/*.mjs",
"lint:unused": "find-unused-exports --module-glob 'src/**/*.mjs'",
"prepublishOnly": "yarn run lint && yarn test",
"refresh": "yarn run clean && yarn run build && yarn run docs",
"setup-test-browser": "http-server docs/test -p 8000 > /dev/null 2>&1 &",
"test": "mocha test/*.js",
"test-browser": "nightwatch -e chrome,chrome_old,firefox,firefox_old,firefox_esr,safari,safari_old"
},
"devDependencies": {
"@babel/cli": "^7.28.0",
"@babel/core": "^7.28.4",
"@babel/plugin-transform-modules-commonjs": "^7.27.1",
"@types/nightwatch": "^3.0.1",
"@types/node": "^24.5.2",
"babel-plugin-replace-import-extension": "^1.1.5",
"browserslist": "^4.26.2",
"concurrently": "^9.2.1",
"eslint": "^8.57.1",
"eslint-plugin-import": "^2.32.0",
"eslint-plugin-jsdoc": "^60.5.0",
"espower-cli": "^1.1.0",
"espower-loader": "^1.2.2",
"exorcist": "^2.0.0",
"find-unused-exports": "^7.1.1",
"http-server": "^14.1.1",
"mocha": "^11.7.2",
"nightwatch": "^3.12.2",
"nightwatch-saucelabs-endsauce": "^2.4.0",
"nyc": "^17.1.0",
"power-assert": "^1.4.2",
"rollup": "^4.52.2",
"rollup-plugin-cleanup": "^3.2.1",
"source-map-support": "^0.5.21"
},
"packageManager": "yarn@1.22.22"
}
-35
View File
@@ -1,35 +0,0 @@
import { safeIfNeeded } from "./_util/arrayIterator.mjs";
import { convertToNumber, roundToFloat16Bits } from "./_util/converter.mjs";
import {
DataViewPrototypeGetUint16,
DataViewPrototypeSetUint16,
} from "./_util/primordials.mjs";
/**
* returns an unsigned 16-bit float at the specified byte offset from the start of the DataView
* @param {DataView} dataView
* @param {number} byteOffset
* @param {[boolean]} opts
* @returns {number}
*/
export function getFloat16(dataView, byteOffset, ...opts) {
return convertToNumber(
DataViewPrototypeGetUint16(dataView, byteOffset, ...safeIfNeeded(opts))
);
}
/**
* stores an unsigned 16-bit float value at the specified byte offset from the start of the DataView
* @param {DataView} dataView
* @param {number} byteOffset
* @param {number} value
* @param {[boolean]} opts
*/
export function setFloat16(dataView, byteOffset, value, ...opts) {
return DataViewPrototypeSetUint16(
dataView,
byteOffset,
roundToFloat16Bits(value),
...safeIfNeeded(opts)
);
}
File diff suppressed because it is too large Load Diff
-86
View File
@@ -1,86 +0,0 @@
import {
ArrayIteratorPrototype,
ArrayIteratorPrototypeNext,
ArrayPrototypeSymbolIterator,
GeneratorPrototypeNext,
IteratorPrototype,
NativeArrayPrototypeSymbolIterator,
NativeWeakMap,
ObjectCreate,
ObjectDefineProperty,
ReflectGetOwnPropertyDescriptor,
ReflectOwnKeys,
SymbolIterator,
WeakMapPrototypeGet,
WeakMapPrototypeSet,
} from "./primordials.mjs";
/** @type {WeakMap<{}, IterableIterator<any>>} */
const arrayIterators = new NativeWeakMap();
const SafeIteratorPrototype = ObjectCreate(null, {
next: {
value: function next() {
const arrayIterator = WeakMapPrototypeGet(arrayIterators, this);
return ArrayIteratorPrototypeNext(arrayIterator);
},
},
[SymbolIterator]: {
value: function values() {
return this;
},
},
});
/**
* Wrap the Array around the SafeIterator If Array.prototype [@@iterator] has been modified
* @type {<T>(array: T[]) => Iterable<T>}
*/
export function safeIfNeeded(array) {
if (
array[SymbolIterator] === NativeArrayPrototypeSymbolIterator &&
ArrayIteratorPrototype.next === ArrayIteratorPrototypeNext
) {
return array;
}
const safe = ObjectCreate(SafeIteratorPrototype);
WeakMapPrototypeSet(arrayIterators, safe, ArrayPrototypeSymbolIterator(array));
return safe;
}
/** @type {WeakMap<{}, Generator<any>>} */
const generators = new NativeWeakMap();
/** @see https://tc39.es/ecma262/#sec-%arrayiteratorprototype%-object */
const DummyArrayIteratorPrototype = ObjectCreate(IteratorPrototype, {
next: {
value: function next() {
const generator = WeakMapPrototypeGet(generators, this);
return GeneratorPrototypeNext(generator);
},
writable: true,
configurable: true,
},
});
for (const key of ReflectOwnKeys(ArrayIteratorPrototype)) {
// next method has already defined
if (key === "next") {
continue;
}
// Copy ArrayIteratorPrototype descriptors to DummyArrayIteratorPrototype
ObjectDefineProperty(DummyArrayIteratorPrototype, key, ReflectGetOwnPropertyDescriptor(ArrayIteratorPrototype, key));
}
/**
* Wrap the Generator around the dummy ArrayIterator
* @type {<T>(generator: Generator<T>) => IterableIterator<T>}
*/
export function wrap(generator) {
const dummy = ObjectCreate(DummyArrayIteratorPrototype);
WeakMapPrototypeSet(generators, dummy, generator);
return dummy;
}
-31
View File
@@ -1,31 +0,0 @@
import { isObject, isObjectLike } from "./is.mjs";
import { THE_CONSTRUCTOR_PROPERTY_VALUE_IS_NOT_AN_OBJECT } from "./messages.mjs";
import { NativeTypeError, ReflectGetPrototypeOf, ReflectHas, SymbolFor } from "./primordials.mjs";
export const brand = SymbolFor("__Float16Array__");
/**
* @param {unknown} target
* @throws {TypeError}
* @returns {boolean}
*/
export function hasFloat16ArrayBrand(target) {
if (!isObjectLike(target)) {
return false;
}
const prototype = ReflectGetPrototypeOf(target);
if (!isObjectLike(prototype)) {
return false;
}
const constructor = prototype.constructor;
if (constructor === undefined) {
return false;
}
if (!isObject(constructor)) {
throw NativeTypeError(THE_CONSTRUCTOR_PROPERTY_VALUE_IS_NOT_AN_OBJECT);
}
return ReflectHas(constructor, brand);
}
-173
View File
@@ -1,173 +0,0 @@
import {
EPSILON,
MathAbs,
NativeArrayBuffer,
NativeFloat32Array,
NativeUint16Array,
NativeUint32Array,
NativeUint8Array,
NumberIsFinite,
NumberIsNaN,
} from "./primordials.mjs";
const INVERSE_OF_EPSILON = 1 / EPSILON;
/**
* rounds to the nearest value;
* if the number falls midway, it is rounded to the nearest value with an even least significant digit
* @param {number} num
* @returns {number}
*/
function roundTiesToEven(num) {
return (num + INVERSE_OF_EPSILON) - INVERSE_OF_EPSILON;
}
const FLOAT16_MIN_VALUE = 6.103515625e-05;
const FLOAT16_MAX_VALUE = 65504;
const FLOAT16_EPSILON = 0.0009765625;
const FLOAT16_EPSILON_MULTIPLIED_BY_FLOAT16_MIN_VALUE = FLOAT16_EPSILON * FLOAT16_MIN_VALUE;
const FLOAT16_EPSILON_DEVIDED_BY_EPSILON = FLOAT16_EPSILON * INVERSE_OF_EPSILON;
/**
* round a number to a half float number
* @param {unknown} num - double float
* @returns {number} half float number
*/
export function roundToFloat16(num) {
const number = +num;
// NaN, Infinity, -Infinity, 0, -0
if (!NumberIsFinite(number) || number === 0) {
return number;
}
// finite except 0, -0
const sign = number > 0 ? 1 : -1;
const absolute = MathAbs(number);
// small number
if (absolute < FLOAT16_MIN_VALUE) {
return sign * roundTiesToEven(absolute / FLOAT16_EPSILON_MULTIPLIED_BY_FLOAT16_MIN_VALUE) * FLOAT16_EPSILON_MULTIPLIED_BY_FLOAT16_MIN_VALUE;
}
const temp = (1 + FLOAT16_EPSILON_DEVIDED_BY_EPSILON) * absolute;
const result = temp - (temp - absolute);
// large number
if (result > FLOAT16_MAX_VALUE || NumberIsNaN(result)) {
return sign * Infinity;
}
return sign * result;
}
// base algorithm: http://fox-toolkit.org/ftp/fasthalffloatconversion.pdf
const buffer = new NativeArrayBuffer(4);
const floatView = new NativeFloat32Array(buffer);
const uint32View = new NativeUint32Array(buffer);
const baseTable = new NativeUint16Array(512);
const shiftTable = new NativeUint8Array(512);
for (let i = 0; i < 256; ++i) {
const e = i - 127;
// very small number (0, -0)
if (e < -24) {
baseTable[i] = 0x0000;
baseTable[i | 0x100] = 0x8000;
shiftTable[i] = 24;
shiftTable[i | 0x100] = 24;
// small number (denorm)
} else if (e < -14) {
baseTable[i] = 0x0400 >> (-e - 14);
baseTable[i | 0x100] = (0x0400 >> (-e - 14)) | 0x8000;
shiftTable[i] = -e - 1;
shiftTable[i | 0x100] = -e - 1;
// normal number
} else if (e <= 15) {
baseTable[i] = (e + 15) << 10;
baseTable[i | 0x100] = ((e + 15) << 10) | 0x8000;
shiftTable[i] = 13;
shiftTable[i | 0x100] = 13;
// large number (Infinity, -Infinity)
} else if (e < 128) {
baseTable[i] = 0x7c00;
baseTable[i | 0x100] = 0xfc00;
shiftTable[i] = 24;
shiftTable[i | 0x100] = 24;
// stay (NaN, Infinity, -Infinity)
} else {
baseTable[i] = 0x7c00;
baseTable[i | 0x100] = 0xfc00;
shiftTable[i] = 13;
shiftTable[i | 0x100] = 13;
}
}
/**
* round a number to a half float number bits
* @param {unknown} num - double float
* @returns {number} half float number bits
*/
export function roundToFloat16Bits(num) {
floatView[0] = roundToFloat16(num);
const f = uint32View[0];
const e = (f >> 23) & 0x1ff;
return baseTable[e] + ((f & 0x007fffff) >> shiftTable[e]);
}
const mantissaTable = new NativeUint32Array(2048);
for (let i = 1; i < 1024; ++i) {
let m = i << 13; // zero pad mantissa bits
let e = 0; // zero exponent
// normalized
while ((m & 0x00800000) === 0) {
m <<= 1;
e -= 0x00800000; // decrement exponent
}
m &= ~0x00800000; // clear leading 1 bit
e += 0x38800000; // adjust bias
mantissaTable[i] = m | e;
}
for (let i = 1024; i < 2048; ++i) {
mantissaTable[i] = 0x38000000 + ((i - 1024) << 13);
}
const exponentTable = new NativeUint32Array(64);
for (let i = 1; i < 31; ++i) {
exponentTable[i] = i << 23;
}
exponentTable[31] = 0x47800000;
exponentTable[32] = 0x80000000;
for (let i = 33; i < 63; ++i) {
exponentTable[i] = 0x80000000 + ((i - 32) << 23);
}
exponentTable[63] = 0xc7800000;
const offsetTable = new NativeUint16Array(64);
for (let i = 1; i < 64; ++i) {
if (i !== 32) {
offsetTable[i] = 1024;
}
}
/**
* convert a half float number bits to a number
* @param {number} float16bits - half float number bits
* @returns {number} double float
*/
export function convertToNumber(float16bits) {
const i = float16bits >> 10;
uint32View[0] = mantissaTable[offsetTable[i] + (float16bits & 0x3ff)] + exponentTable[i];
return floatView[0];
}
-151
View File
@@ -1,151 +0,0 @@
import {
ArrayBufferPrototypeGetByteLength,
ArrayIsArray,
ArrayIteratorPrototype,
ArrayIteratorPrototypeNext,
MathTrunc,
NativeArrayPrototypeSymbolIterator,
NativeSharedArrayBuffer,
NativeTypedArrayPrototypeSymbolIterator,
NumberIsFinite,
SharedArrayBufferPrototypeGetByteLength,
SymbolIterator,
TypedArrayPrototypeGetSymbolToStringTag,
} from "./primordials.mjs";
/**
* @param {unknown} value
* @returns {value is {}}
*/
export function isObject(value) {
return (
(value !== null && typeof value === "object") ||
typeof value === "function"
);
}
/**
* @param {unknown} value
* @returns {value is {}}
*/
export function isObjectLike(value) {
return value !== null && typeof value === "object";
}
// Inspired by util.types implementation of Node.js
/** @typedef {Uint8Array|Uint8ClampedArray|Uint16Array|Uint32Array|Int8Array|Int16Array|Int32Array|Float32Array|Float64Array|BigUint64Array|BigInt64Array} TypedArray */
/**
* @param {unknown} value
* @returns {value is TypedArray}
*/
export function isNativeTypedArray(value) {
return TypedArrayPrototypeGetSymbolToStringTag(value) !== undefined;
}
/**
* @param {unknown} value
* @returns {value is BigInt64Array|BigUint64Array}
*/
export function isNativeBigIntTypedArray(value) {
const typedArrayName = TypedArrayPrototypeGetSymbolToStringTag(value);
return (
typedArrayName === "BigInt64Array" ||
typedArrayName === "BigUint64Array"
);
}
/**
* @param {unknown} value
* @returns {value is ArrayBuffer}
*/
function isArrayBuffer(value) {
try {
// ArrayBuffers are never arrays
if (ArrayIsArray(value)) {
return false;
}
ArrayBufferPrototypeGetByteLength(/** @type {any} */ (value));
return true;
} catch (e) {
return false;
}
}
/**
* @param {unknown} value
* @returns {value is SharedArrayBuffer}
*/
export function isSharedArrayBuffer(value) {
if (NativeSharedArrayBuffer === null) {
return false;
}
try {
SharedArrayBufferPrototypeGetByteLength(/** @type {any} */ (value));
return true;
} catch (e) {
return false;
}
}
/**
* @param {unknown} value
* @returns {value is ArrayBuffer|SharedArrayBuffer}
*/
export function isAnyArrayBuffer(value) {
return isArrayBuffer(value) || isSharedArrayBuffer(value);
}
/**
* @param {unknown} value
* @returns {value is unknown[]}
*/
export function isOrdinaryArray(value) {
if (!ArrayIsArray(value)) {
return false;
}
// Verify that there are no changes in ArrayIterator
return (
value[SymbolIterator] === NativeArrayPrototypeSymbolIterator &&
ArrayIteratorPrototype.next === ArrayIteratorPrototypeNext
);
}
/**
* @param {unknown} value
* @returns {value is TypedArray}
*/
export function isOrdinaryNativeTypedArray(value) {
if (!isNativeTypedArray(value)) {
return false;
}
// Verify that there are no changes in ArrayIterator
return (
value[SymbolIterator] === NativeTypedArrayPrototypeSymbolIterator &&
ArrayIteratorPrototype.next === ArrayIteratorPrototypeNext
);
}
/**
* @param {unknown} value
* @returns {value is string}
*/
export function isCanonicalIntegerIndexString(value) {
if (typeof value !== "string") {
return false;
}
const number = +value;
if (value !== number + "") {
return false;
}
if (!NumberIsFinite(number)) {
return false;
}
return number === MathTrunc(number);
}
-22
View File
@@ -1,22 +0,0 @@
export const THIS_IS_NOT_AN_OBJECT = "This is not an object";
export const THIS_IS_NOT_A_FLOAT16ARRAY_OBJECT = "This is not a Float16Array object";
export const THIS_CONSTRUCTOR_IS_NOT_A_SUBCLASS_OF_FLOAT16ARRAY =
"This constructor is not a subclass of Float16Array";
export const THE_CONSTRUCTOR_PROPERTY_VALUE_IS_NOT_AN_OBJECT =
"The constructor property value is not an object";
export const SPECIES_CONSTRUCTOR_DIDNT_RETURN_TYPEDARRAY_OBJECT =
"Species constructor didn't return TypedArray object";
export const DERIVED_CONSTRUCTOR_CREATED_TYPEDARRAY_OBJECT_WHICH_WAS_TOO_SMALL_LENGTH =
"Derived constructor created TypedArray object which was too small length";
export const ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER =
"Attempting to access detached ArrayBuffer";
export const CANNOT_CONVERT_UNDEFINED_OR_NULL_TO_OBJECT =
"Cannot convert undefined or null to object";
export const CANNOT_MIX_BIGINT_AND_OTHER_TYPES =
"Cannot mix BigInt and other types, use explicit conversions";
export const ITERATOR_PROPERTY_IS_NOT_CALLABLE = "@@iterator property is not callable";
export const REDUCE_OF_EMPTY_ARRAY_WITH_NO_INITIAL_VALUE =
"Reduce of empty array with no initial value";
export const THE_COMPARISON_FUNCTION_MUST_BE_EITHER_A_FUNCTION_OR_UNDEFINED =
"The comparison function must be either a function or undefined";
export const OFFSET_IS_OUT_OF_BOUNDS = "Offset is out of bounds";
-254
View File
@@ -1,254 +0,0 @@
/* eslint-disable no-restricted-globals, no-restricted-syntax */
/* global SharedArrayBuffer */
import { CANNOT_CONVERT_UNDEFINED_OR_NULL_TO_OBJECT } from "./messages.mjs";
/** @type {<T extends (...args: any) => any>(target: T) => (thisArg: ThisType<T>, ...args: any[]) => any} */
function uncurryThis(target) {
return (thisArg, ...args) => {
return ReflectApply(target, thisArg, args);
};
}
/** @type {(target: any, key: string | symbol) => (thisArg: any, ...args: any[]) => any} */
function uncurryThisGetter(target, key) {
return uncurryThis(
ReflectGetOwnPropertyDescriptor(
target,
key
).get
);
}
// Reflect
export const {
apply: ReflectApply,
construct: ReflectConstruct,
defineProperty: ReflectDefineProperty,
get: ReflectGet,
getOwnPropertyDescriptor: ReflectGetOwnPropertyDescriptor,
getPrototypeOf: ReflectGetPrototypeOf,
has: ReflectHas,
ownKeys: ReflectOwnKeys,
set: ReflectSet,
setPrototypeOf: ReflectSetPrototypeOf,
} = Reflect;
// Proxy
export const NativeProxy = Proxy;
// Number
export const {
EPSILON,
MAX_SAFE_INTEGER,
isFinite: NumberIsFinite,
isNaN: NumberIsNaN,
} = Number;
// Symbol
export const {
iterator: SymbolIterator,
species: SymbolSpecies,
toStringTag: SymbolToStringTag,
for: SymbolFor,
} = Symbol;
// Object
export const NativeObject = Object;
export const {
create: ObjectCreate,
defineProperty: ObjectDefineProperty,
freeze: ObjectFreeze,
is: ObjectIs,
} = NativeObject;
const ObjectPrototype = NativeObject.prototype;
/** @type {(object: object, key: PropertyKey) => Function | undefined} */
export const ObjectPrototype__lookupGetter__ = /** @type {any} */ (ObjectPrototype).__lookupGetter__
? uncurryThis(/** @type {any} */ (ObjectPrototype).__lookupGetter__)
: (object, key) => {
if (object == null) {
throw NativeTypeError(
CANNOT_CONVERT_UNDEFINED_OR_NULL_TO_OBJECT
);
}
let target = NativeObject(object);
do {
const descriptor = ReflectGetOwnPropertyDescriptor(target, key);
if (descriptor !== undefined) {
if (ObjectHasOwn(descriptor, "get")) {
return descriptor.get;
}
return;
}
} while ((target = ReflectGetPrototypeOf(target)) !== null);
};
/** @type {(object: object, key: PropertyKey) => boolean} */
export const ObjectHasOwn = /** @type {any} */ (NativeObject).hasOwn ||
uncurryThis(ObjectPrototype.hasOwnProperty);
// Array
const NativeArray = Array;
export const ArrayIsArray = NativeArray.isArray;
const ArrayPrototype = NativeArray.prototype;
/** @type {(array: ArrayLike<unknown>, separator?: string) => string} */
export const ArrayPrototypeJoin = uncurryThis(ArrayPrototype.join);
/** @type {<T>(array: T[], ...items: T[]) => number} */
export const ArrayPrototypePush = uncurryThis(ArrayPrototype.push);
/** @type {(array: ArrayLike<unknown>, ...opts: any[]) => string} */
export const ArrayPrototypeToLocaleString = uncurryThis(
ArrayPrototype.toLocaleString
);
export const NativeArrayPrototypeSymbolIterator = ArrayPrototype[SymbolIterator];
/** @type {<T>(array: T[]) => IterableIterator<T>} */
export const ArrayPrototypeSymbolIterator = uncurryThis(NativeArrayPrototypeSymbolIterator);
// Math
export const {
abs: MathAbs,
trunc: MathTrunc,
} = Math;
// ArrayBuffer
export const NativeArrayBuffer = ArrayBuffer;
export const ArrayBufferIsView = NativeArrayBuffer.isView;
const ArrayBufferPrototype = NativeArrayBuffer.prototype;
/** @type {(buffer: ArrayBuffer, begin?: number, end?: number) => number} */
export const ArrayBufferPrototypeSlice = uncurryThis(ArrayBufferPrototype.slice);
/** @type {(buffer: ArrayBuffer) => ArrayBuffer} */
export const ArrayBufferPrototypeGetByteLength = uncurryThisGetter(ArrayBufferPrototype, "byteLength");
// SharedArrayBuffer
export const NativeSharedArrayBuffer = typeof SharedArrayBuffer !== "undefined" ? SharedArrayBuffer : null;
/** @type {(buffer: SharedArrayBuffer) => SharedArrayBuffer} */
export const SharedArrayBufferPrototypeGetByteLength = NativeSharedArrayBuffer
&& uncurryThisGetter(NativeSharedArrayBuffer.prototype, "byteLength");
// TypedArray
/** @typedef {Uint8Array|Uint8ClampedArray|Uint16Array|Uint32Array|Int8Array|Int16Array|Int32Array|Float32Array|Float64Array|BigUint64Array|BigInt64Array} TypedArray */
/** @type {any} */
export const TypedArray = ReflectGetPrototypeOf(Uint8Array);
const TypedArrayFrom = TypedArray.from;
export const TypedArrayPrototype = TypedArray.prototype;
export const NativeTypedArrayPrototypeSymbolIterator = TypedArrayPrototype[SymbolIterator];
/** @type {(typedArray: TypedArray) => IterableIterator<number>} */
export const TypedArrayPrototypeKeys = uncurryThis(TypedArrayPrototype.keys);
/** @type {(typedArray: TypedArray) => IterableIterator<number>} */
export const TypedArrayPrototypeValues = uncurryThis(
TypedArrayPrototype.values
);
/** @type {(typedArray: TypedArray) => IterableIterator<[number, number]>} */
export const TypedArrayPrototypeEntries = uncurryThis(
TypedArrayPrototype.entries
);
/** @type {(typedArray: TypedArray, array: ArrayLike<number>, offset?: number) => void} */
export const TypedArrayPrototypeSet = uncurryThis(TypedArrayPrototype.set);
/** @type {<T extends TypedArray>(typedArray: T) => T} */
export const TypedArrayPrototypeReverse = uncurryThis(
TypedArrayPrototype.reverse
);
/** @type {<T extends TypedArray>(typedArray: T, value: number, start?: number, end?: number) => T} */
export const TypedArrayPrototypeFill = uncurryThis(TypedArrayPrototype.fill);
/** @type {<T extends TypedArray>(typedArray: T, target: number, start: number, end?: number) => T} */
export const TypedArrayPrototypeCopyWithin = uncurryThis(
TypedArrayPrototype.copyWithin
);
/** @type {<T extends TypedArray>(typedArray: T, compareFn?: (a: number, b: number) => number) => T} */
export const TypedArrayPrototypeSort = uncurryThis(TypedArrayPrototype.sort);
/** @type {<T extends TypedArray>(typedArray: T, start?: number, end?: number) => T} */
export const TypedArrayPrototypeSlice = uncurryThis(TypedArrayPrototype.slice);
/** @type {<T extends TypedArray>(typedArray: T, start?: number, end?: number) => T} */
export const TypedArrayPrototypeSubarray = uncurryThis(
TypedArrayPrototype.subarray
);
/** @type {((typedArray: TypedArray) => ArrayBuffer)} */
export const TypedArrayPrototypeGetBuffer = uncurryThisGetter(
TypedArrayPrototype,
"buffer"
);
/** @type {((typedArray: TypedArray) => number)} */
export const TypedArrayPrototypeGetByteOffset = uncurryThisGetter(
TypedArrayPrototype,
"byteOffset"
);
/** @type {((typedArray: TypedArray) => number)} */
export const TypedArrayPrototypeGetLength = uncurryThisGetter(
TypedArrayPrototype,
"length"
);
/** @type {(target: unknown) => string} */
export const TypedArrayPrototypeGetSymbolToStringTag = uncurryThisGetter(
TypedArrayPrototype,
SymbolToStringTag
);
// Uint8Array
export const NativeUint8Array = Uint8Array;
// Uint16Array
export const NativeUint16Array = Uint16Array;
/** @type {Uint16ArrayConstructor["from"]} */
export const Uint16ArrayFrom = (...args) => {
return ReflectApply(TypedArrayFrom, NativeUint16Array, args);
};
// Uint32Array
export const NativeUint32Array = Uint32Array;
// Float32Array
export const NativeFloat32Array = Float32Array;
// ArrayIterator
/** @type {any} */
export const ArrayIteratorPrototype = ReflectGetPrototypeOf([][SymbolIterator]());
/** @type {<T>(arrayIterator: IterableIterator<T>) => IteratorResult<T>} */
export const ArrayIteratorPrototypeNext = uncurryThis(ArrayIteratorPrototype.next);
// Generator
/** @type {<T = unknown, TReturn = any, TNext = unknown>(generator: Generator<T, TReturn, TNext>, value?: TNext) => T} */
export const GeneratorPrototypeNext = uncurryThis((function* () {})().next);
// Iterator
export const IteratorPrototype = ReflectGetPrototypeOf(ArrayIteratorPrototype);
// DataView
const DataViewPrototype = DataView.prototype;
/** @type {(dataView: DataView, byteOffset: number, littleEndian?: boolean) => number} */
export const DataViewPrototypeGetUint16 = uncurryThis(
DataViewPrototype.getUint16
);
/** @type {(dataView: DataView, byteOffset: number, value: number, littleEndian?: boolean) => void} */
export const DataViewPrototypeSetUint16 = uncurryThis(
DataViewPrototype.setUint16
);
// Error
export const NativeTypeError = TypeError;
export const NativeRangeError = RangeError;
// WeakSet
/**
* Do not construct with arguments to avoid calling the "add" method
* @type {{new <T extends {}>(): WeakSet<T>}}
*/
export const NativeWeakSet = WeakSet;
const WeakSetPrototype = NativeWeakSet.prototype;
/** @type {<T extends {}>(set: WeakSet<T>, value: T) => Set<T>} */
export const WeakSetPrototypeAdd = uncurryThis(WeakSetPrototype.add);
/** @type {<T extends {}>(set: WeakSet<T>, value: T) => boolean} */
export const WeakSetPrototypeHas = uncurryThis(WeakSetPrototype.has);
// WeakMap
/**
* Do not construct with arguments to avoid calling the "set" method
* @type {{new <K extends {}, V>(): WeakMap<K, V>}}
*/
export const NativeWeakMap = WeakMap;
const WeakMapPrototype = NativeWeakMap.prototype;
/** @type {<K extends {}, V>(weakMap: WeakMap<K, V>, key: K) => V} */
export const WeakMapPrototypeGet = uncurryThis(WeakMapPrototype.get);
/** @type {<K extends {}, V>(weakMap: WeakMap<K, V>, key: K) => boolean} */
export const WeakMapPrototypeHas = uncurryThis(WeakMapPrototype.has);
/** @type {<K extends {}, V>(weakMap: WeakMap<K, V>, key: K, value: V) => WeakMap} */
export const WeakMapPrototypeSet = uncurryThis(WeakMapPrototype.set);
-137
View File
@@ -1,137 +0,0 @@
import { isObject, isSharedArrayBuffer } from "./is.mjs";
import {
THE_CONSTRUCTOR_PROPERTY_VALUE_IS_NOT_AN_OBJECT,
THIS_IS_NOT_AN_OBJECT,
} from "./messages.mjs";
import {
ArrayBufferPrototypeSlice,
MAX_SAFE_INTEGER,
MathTrunc,
NativeTypeError,
NumberIsNaN,
ObjectIs,
SymbolSpecies,
} from "./primordials.mjs";
/**
* @see https://tc39.es/ecma262/#sec-tointegerorinfinity
* @param {unknown} target
* @returns {number}
*/
export function ToIntegerOrInfinity(target) {
const number = +target;
if (NumberIsNaN(number) || number === 0) {
return 0;
}
return MathTrunc(number);
}
/**
* @see https://tc39.es/ecma262/#sec-tolength
* @param {unknown} target
* @returns {number}
*/
export function ToLength(target) {
const length = ToIntegerOrInfinity(target);
if (length < 0) {
return 0;
}
return length < MAX_SAFE_INTEGER
? length
: MAX_SAFE_INTEGER;
}
/**
* @see https://tc39.es/ecma262/#sec-speciesconstructor
* @param {object} target
* @param {{ new(...args: any[]): any; }} defaultConstructor
* @returns {{ new(...args: any[]): any; }}
*/
export function SpeciesConstructor(target, defaultConstructor) {
if (!isObject(target)) {
throw NativeTypeError(THIS_IS_NOT_AN_OBJECT);
}
const constructor = target.constructor;
if (constructor === undefined) {
return defaultConstructor;
}
if (!isObject(constructor)) {
throw NativeTypeError(THE_CONSTRUCTOR_PROPERTY_VALUE_IS_NOT_AN_OBJECT);
}
const species = constructor[SymbolSpecies];
if (species == null) {
return defaultConstructor;
}
return species;
}
/**
* @see https://tc39.es/ecma262/#sec-isdetachedbuffer
* @param {ArrayBufferLike} buffer
* @returns {boolean}
*/
export function IsDetachedBuffer(buffer) {
if (isSharedArrayBuffer(buffer)) {
return false;
}
try {
ArrayBufferPrototypeSlice(buffer, 0, 0);
return false;
} catch (e) {/* empty */}
return true;
}
/**
* bigint comparisons are not supported
* @see https://tc39.es/ecma262/#sec-%typedarray%.prototype.sort
* @param {number} x
* @param {number} y
* @returns {-1 | 0 | 1}
*/
export function defaultCompare(x, y) {
const isXNaN = NumberIsNaN(x);
const isYNaN = NumberIsNaN(y);
if (isXNaN && isYNaN) {
return 0;
}
if (isXNaN) {
return 1;
}
if (isYNaN) {
return -1;
}
if (x < y) {
return -1;
}
if (x > y) {
return 1;
}
if (x === 0 && y === 0) {
const isXPlusZero = ObjectIs(x, 0);
const isYPlusZero = ObjectIs(y, 0);
if (!isXPlusZero && isYPlusZero) {
return -1;
}
if (isXPlusZero && !isYPlusZero) {
return 1;
}
}
return 0;
}
-10
View File
@@ -1,10 +0,0 @@
import { roundToFloat16 } from "./_util/converter.mjs";
/**
* returns the nearest half-precision float representation of a number
* @param {number} x
* @returns {number}
*/
export function f16round(x) {
return roundToFloat16(x);
}
-7
View File
@@ -1,7 +0,0 @@
/* ignore unused exports */
// @ts-self-types="../index.v5.7.d.ts"
export { Float16Array, isFloat16Array } from "./Float16Array.mjs";
export { isTypedArray } from "./isTypedArray.mjs";
export { getFloat16, setFloat16 } from "./DataView.mjs";
export { f16round, f16round as hfround } from "./f16round.mjs";
-10
View File
@@ -1,10 +0,0 @@
import { isFloat16Array } from "./Float16Array.mjs";
import { isNativeTypedArray } from "./_util/is.mjs";
/**
* @param {unknown} target
* @returns {value is Uint8Array|Uint8ClampedArray|Uint16Array|Uint32Array|Int8Array|Int16Array|Int32Array|Float16Array|Float32Array|Float64Array|BigUint64Array|BigInt64Array}
*/
export function isTypedArray(target) {
return isNativeTypedArray(target) || isFloat16Array(target);
}
-21
View File
@@ -1,21 +0,0 @@
MIT License
Copyright (c) Microsoft Corporation.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
-16
View File
@@ -1,16 +0,0 @@
# Installation
> `npm install --save @types/react-dom`
# Summary
This package contains type definitions for react-dom (https://react.dev/).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/react-dom.
### Additional Details
* Last updated: Wed, 12 Nov 2025 04:37:38 GMT
* Dependencies: none
* Peer dependencies: [@types/react](https://npmjs.com/package/@types/react)
# Credits
These definitions were written by [Asana](https://asana.com), [AssureSign](http://www.assuresign.com), [Microsoft](https://microsoft.com), [MartynasZilinskas](https://github.com/MartynasZilinskas), [Josh Rutherford](https://github.com/theruther4d), [Jessica Franco](https://github.com/Jessidhia), and [Sebastian Silbermann](https://github.com/eps1lon).
-71
View File
@@ -1,71 +0,0 @@
/* eslint-disable @definitelytyped/no-self-import -- self-imports in module augmentations aren't self-imports */
/* eslint-disable @definitelytyped/no-declare-current-package -- The module augmentations are optional */
/**
* These are types for things that are present in the upcoming React 18 release.
*
* Once React 18 is released they can just be moved to the main index file.
*
* To load the types declared here in an actual project, there are three ways. The easiest one,
* if your `tsconfig.json` already has a `"types"` array in the `"compilerOptions"` section,
* is to add `"react-dom/canary"` to the `"types"` array.
*
* Alternatively, a specific import syntax can to be used from a typescript file.
* This module does not exist in reality, which is why the {} is important:
*
* ```ts
* import {} from 'react-dom/canary'
* ```
*
* It is also possible to include it through a triple-slash reference:
*
* ```ts
* /// <reference types="react-dom/canary" />
* ```
*
* Either the import or the reference only needs to appear once, anywhere in the project.
*/
// See https://github.com/facebook/react/blob/main/packages/react-dom/index.js to see how the exports are declared,
// but confirm with published source code (e.g. https://unpkg.com/react-dom@canary) that these exports end up in the published code
import React = require("react");
import ReactDOM = require(".");
export {};
declare module "react" {
// @enableViewTransition
interface ViewTransitionPseudoElement extends Animatable {
getComputedStyle: () => CSSStyleDeclaration;
}
interface ViewTransitionInstance {
group: ViewTransitionPseudoElement;
imagePair: ViewTransitionPseudoElement;
old: ViewTransitionPseudoElement;
new: ViewTransitionPseudoElement;
}
// @enableFragmentRefs
interface FragmentInstance {
blur: () => void;
focus: (focusOptions?: FocusOptions | undefined) => void;
focusLast: (focusOptions?: FocusOptions | undefined) => void;
observeUsing(observer: IntersectionObserver | ResizeObserver): void;
unobserveUsing(observer: IntersectionObserver | ResizeObserver): void;
getClientRects(): Array<DOMRect>;
getRootNode(getRootNodeOptions?: GetRootNodeOptions | undefined): Document | ShadowRoot | FragmentInstance;
addEventListener(
type: string,
listener: EventListener,
optionsOrUseCapture?: Parameters<Element["addEventListener"]>[2],
): void;
removeEventListener(
type: string,
listener: EventListener,
optionsOrUseCapture?: Parameters<Element["removeEventListener"]>[2],
): void;
dispatchEvent(event: Event): boolean;
scrollIntoView(alignToTop?: boolean): void;
}
}
-105
View File
@@ -1,105 +0,0 @@
/**
* WARNING: This entrypoint is only available starting with `react-dom@18.0.0-rc.1`
*/
// See https://github.com/facebook/react/blob/main/packages/react-dom/client.js to see how the exports are declared,
import React = require("react");
export {};
declare const REACT_FORM_STATE_SIGIL: unique symbol;
export interface ReactFormState {
[REACT_FORM_STATE_SIGIL]: never;
}
export interface HydrationOptions {
formState?: ReactFormState | null;
/**
* Prefix for `useId`.
*/
identifierPrefix?: string;
onUncaughtError?:
| ((error: unknown, errorInfo: { componentStack?: string | undefined }) => void)
| undefined;
onRecoverableError?: (error: unknown, errorInfo: ErrorInfo) => void;
onCaughtError?:
| ((
error: unknown,
errorInfo: {
componentStack?: string | undefined;
errorBoundary?: React.Component<unknown> | undefined;
},
) => void)
| undefined;
}
export interface RootOptions {
/**
* Prefix for `useId`.
*/
identifierPrefix?: string;
onUncaughtError?:
| ((error: unknown, errorInfo: { componentStack?: string | undefined }) => void)
| undefined;
onRecoverableError?: (error: unknown, errorInfo: ErrorInfo) => void;
onCaughtError?:
| ((
error: unknown,
errorInfo: {
componentStack?: string | undefined;
errorBoundary?: React.Component<unknown> | undefined;
},
) => void)
| undefined;
}
export interface ErrorInfo {
componentStack?: string;
}
export interface Root {
render(children: React.ReactNode): void;
unmount(): void;
}
/**
* Different release channels declare additional types of ReactNode this particular release channel accepts.
* App or library types should never augment this interface.
*/
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_CREATE_ROOT_CONTAINERS {}
export type Container =
| Element
| DocumentFragment
| Document
| DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_CREATE_ROOT_CONTAINERS[
keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_CREATE_ROOT_CONTAINERS
];
/**
* createRoot lets you create a root to display React components inside a browser DOM node.
*
* @see {@link https://react.dev/reference/react-dom/client/createRoot API Reference for `createRoot`}
*/
export function createRoot(container: Container, options?: RootOptions): Root;
/**
* Same as `createRoot()`, but is used to hydrate a container whose HTML contents were rendered by ReactDOMServer.
*
* React will attempt to attach event listeners to the existing markup.
*
* **Example Usage**
*
* ```jsx
* hydrateRoot(document.querySelector('#root'), <App />)
* ```
*
* @see https://react.dev/reference/react-dom/client/hydrateRoot
*/
export function hydrateRoot(
container: Element | Document,
initialChildren: React.ReactNode,
options?: HydrationOptions,
): Root;
-54
View File
@@ -1,54 +0,0 @@
/**
* These are types for things that are present in the `experimental` builds of React but not yet
* on a stable build.
*
* Once they are promoted to stable they can just be moved to the main index file.
*
* To load the types declared here in an actual project, there are three ways. The easiest one,
* if your `tsconfig.json` already has a `"types"` array in the `"compilerOptions"` section,
* is to add `"react-dom/experimental"` to the `"types"` array.
*
* Alternatively, a specific import syntax can to be used from a typescript file.
* This module does not exist in reality, which is why the {} is important:
*
* ```ts
* import {} from 'react-dom/experimental'
* ```
*
* It is also possible to include it through a triple-slash reference:
*
* ```ts
* /// <reference types="react-dom/experimental" />
* ```
*
* Either the import or the reference only needs to appear once, anywhere in the project.
*/
// See https://github.com/facebook/react/blob/main/packages/react-dom/index.experimental.js to see how the exports are declared,
// but confirm with published source code (e.g. https://unpkg.com/react-dom@experimental) that these exports end up in the published code
import React = require("react");
import ReactDOM = require("./canary");
export {};
declare const UNDEFINED_VOID_ONLY: unique symbol;
type VoidOrUndefinedOnly = void | { [UNDEFINED_VOID_ONLY]: never };
declare module "." {
}
declare module "react" {
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface GestureProvider extends AnimationTimeline {}
}
declare module "./client" {
type TransitionIndicatorCleanup = () => VoidOrUndefinedOnly;
interface RootOptions {
onDefaultTransitionIndicator?: (() => void | TransitionIndicatorCleanup) | undefined;
}
interface HydrationOptions {
onDefaultTransitionIndicator?: (() => void | TransitionIndicatorCleanup) | undefined;
}
}
-133
View File
@@ -1,133 +0,0 @@
// NOTE: Users of the `experimental` builds of React should add a reference
// to 'react-dom/experimental' in their project. See experimental.d.ts's top comment
// for reference and documentation on how exactly to do it.
export as namespace ReactDOM;
import { Key, ReactNode, ReactPortal } from "react";
declare module "react" {
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface CacheSignal extends AbortSignal {}
}
export function createPortal(
children: ReactNode,
container: Element | DocumentFragment,
key?: Key | null,
): ReactPortal;
export const version: string;
export function flushSync<R>(fn: () => R): R;
export function unstable_batchedUpdates<A, R>(callback: (a: A) => R, a: A): R;
export function unstable_batchedUpdates<R>(callback: () => R): R;
export interface FormStatusNotPending {
pending: false;
data: null;
method: null;
action: null;
}
export interface FormStatusPending {
pending: true;
data: FormData;
method: string;
action: string | ((formData: FormData) => void | Promise<void>);
}
export type FormStatus = FormStatusPending | FormStatusNotPending;
export function useFormStatus(): FormStatus;
export function useFormState<State>(
action: (state: Awaited<State>) => State | Promise<State>,
initialState: Awaited<State>,
permalink?: string,
): [state: Awaited<State>, dispatch: () => void, isPending: boolean];
export function useFormState<State, Payload>(
action: (state: Awaited<State>, payload: Payload) => State | Promise<State>,
initialState: Awaited<State>,
permalink?: string,
): [state: Awaited<State>, dispatch: (payload: Payload) => void, isPending: boolean];
export function prefetchDNS(href: string): void;
export interface PreconnectOptions {
// Don't create a helper type.
// It would have to be in module scope to be inlined in TS tooltips.
// But then it becomes part of the public API.
// TODO: Upstream to microsoft/TypeScript-DOM-lib-generator -> w3c/webref
// since the spec has a notion of a dedicated type: https://html.spec.whatwg.org/multipage/urls-and-fetching.html#cors-settings-attribute
crossOrigin?: "anonymous" | "use-credentials" | "" | undefined;
}
export function preconnect(href: string, options?: PreconnectOptions): void;
export type PreloadAs =
| "audio"
| "document"
| "embed"
| "fetch"
| "font"
| "image"
| "object"
| "track"
| "script"
| "style"
| "video"
| "worker";
export interface PreloadOptions {
as: PreloadAs;
crossOrigin?: "anonymous" | "use-credentials" | "" | undefined;
fetchPriority?: "high" | "low" | "auto" | undefined;
// TODO: These should only be allowed with `as: 'image'` but it's not trivial to write tests against the full TS support matrix.
imageSizes?: string | undefined;
imageSrcSet?: string | undefined;
integrity?: string | undefined;
type?: string | undefined;
nonce?: string | undefined;
referrerPolicy?: ReferrerPolicy | undefined;
media?: string | undefined;
}
export function preload(href: string, options?: PreloadOptions): void;
// https://html.spec.whatwg.org/multipage/links.html#link-type-modulepreload
export type PreloadModuleAs = RequestDestination;
export interface PreloadModuleOptions {
/**
* @default "script"
*/
as: PreloadModuleAs;
crossOrigin?: "anonymous" | "use-credentials" | "" | undefined;
integrity?: string | undefined;
nonce?: string | undefined;
}
export function preloadModule(href: string, options?: PreloadModuleOptions): void;
export type PreinitAs = "script" | "style";
export interface PreinitOptions {
as: PreinitAs;
crossOrigin?: "anonymous" | "use-credentials" | "" | undefined;
fetchPriority?: "high" | "low" | "auto" | undefined;
precedence?: string | undefined;
integrity?: string | undefined;
nonce?: string | undefined;
}
export function preinit(href: string, options?: PreinitOptions): void;
// Will be expanded to include all of https://github.com/tc39/proposal-import-attributes
export type PreinitModuleAs = "script";
export interface PreinitModuleOptions {
/**
* @default "script"
*/
as?: PreinitModuleAs;
crossOrigin?: "anonymous" | "use-credentials" | "" | undefined;
integrity?: string | undefined;
nonce?: string | undefined;
}
export function preinitModule(href: string, options?: PreinitModuleOptions): void;
export function requestFormReset(form: HTMLFormElement): void;
-128
View File
@@ -1,128 +0,0 @@
{
"name": "@types/react-dom",
"version": "19.2.3",
"description": "TypeScript definitions for react-dom",
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/react-dom",
"license": "MIT",
"contributors": [
{
"name": "Asana",
"url": "https://asana.com"
},
{
"name": "AssureSign",
"url": "http://www.assuresign.com"
},
{
"name": "Microsoft",
"url": "https://microsoft.com"
},
{
"name": "MartynasZilinskas",
"githubUsername": "MartynasZilinskas",
"url": "https://github.com/MartynasZilinskas"
},
{
"name": "Josh Rutherford",
"githubUsername": "theruther4d",
"url": "https://github.com/theruther4d"
},
{
"name": "Jessica Franco",
"githubUsername": "Jessidhia",
"url": "https://github.com/Jessidhia"
},
{
"name": "Sebastian Silbermann",
"githubUsername": "eps1lon",
"url": "https://github.com/eps1lon"
}
],
"main": "",
"types": "index.d.ts",
"exports": {
".": {
"types": {
"default": "./index.d.ts"
}
},
"./client": {
"types": {
"default": "./client.d.ts"
}
},
"./canary": {
"types": {
"default": "./canary.d.ts"
}
},
"./server": {
"types": {
"default": "./server.d.ts"
}
},
"./server.browser": {
"types": {
"default": "./server.browser.d.ts"
}
},
"./server.bun": {
"types": {
"default": "./server.bun.d.ts"
}
},
"./server.edge": {
"types": {
"default": "./server.edge.d.ts"
}
},
"./server.node": {
"types": {
"default": "./server.node.d.ts"
}
},
"./static": {
"types": {
"default": "./static.d.ts"
}
},
"./static.browser": {
"types": {
"default": "./static.browser.d.ts"
}
},
"./static.edge": {
"types": {
"default": "./static.edge.d.ts"
}
},
"./static.node": {
"types": {
"default": "./static.node.d.ts"
}
},
"./experimental": {
"types": {
"default": "./experimental.d.ts"
}
},
"./test-utils": {
"types": {
"default": "./test-utils/index.d.ts"
}
},
"./package.json": "./package.json"
},
"repository": {
"type": "git",
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
"directory": "types/react-dom"
},
"scripts": {},
"dependencies": {},
"peerDependencies": {
"@types/react": "^19.2.0"
},
"typesPublisherContentHash": "6f16aac4f50b7ebe3201fdac53a58874d2899d6108894538ade2d61fbb99f8c5",
"typeScriptVersion": "5.2"
}
-1
View File
@@ -1 +0,0 @@
export { renderToReadableStream, renderToStaticMarkup, renderToString } from "./server";
-1
View File
@@ -1 +0,0 @@
export { renderToReadableStream, renderToStaticMarkup, renderToString } from "./server";
-183
View File
@@ -1,183 +0,0 @@
// forward declarations
declare global {
namespace NodeJS {
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface ReadableStream {}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface WritableStream {}
}
/**
* Stub for https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
*/
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface AbortSignal {}
/**
* Stub for https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream
*/
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface ReadableStream {}
}
import { ReactNode } from "react";
import { ErrorInfo, ReactFormState } from "./client";
import { PostponedState, ResumeOptions } from "./static";
export interface BootstrapScriptDescriptor {
src: string;
integrity?: string | undefined;
crossOrigin?: string | undefined;
}
/**
* @see {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/script/type/importmap Import maps}
*/
// TODO: Ideally TypeScripts standard library would include this type.
// Until then we keep the prefixed one for future compatibility.
export interface ReactImportMap {
/**
* @see {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/script/type/importmap#imports `imports` reference}
*/
imports?: {
[specifier: string]: string;
} | undefined;
/**
* @see {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/script/type/importmap#integrity `integrity` reference}
*/
integrity?: {
[moduleURL: string]: string;
} | undefined;
/**
* @see {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/script/type/importmap#scopes `scopes` reference}
*/
scopes?: {
[scope: string]: {
[specifier: string]: string;
};
} | undefined;
}
export interface RenderToPipeableStreamOptions {
identifierPrefix?: string;
namespaceURI?: string;
nonce?: string;
bootstrapScriptContent?: string;
bootstrapScripts?: Array<string | BootstrapScriptDescriptor>;
bootstrapModules?: Array<string | BootstrapScriptDescriptor>;
/**
* Maximum length of the header content in unicode code units i.e. string.length.
* Must be a positive integer if specified.
* @default 2000
*/
headersLengthHint?: number | undefined;
importMap?: ReactImportMap | undefined;
progressiveChunkSize?: number;
onHeaders?: ((headers: Headers) => void) | undefined;
onShellReady?: () => void;
onShellError?: (error: unknown) => void;
onAllReady?: () => void;
onError?: (error: unknown, errorInfo: ErrorInfo) => string | void;
formState?: ReactFormState | null;
}
export interface PipeableStream {
abort: (reason?: unknown) => void;
pipe: <Writable extends NodeJS.WritableStream>(destination: Writable) => Writable;
}
export interface ServerOptions {
identifierPrefix?: string;
}
/**
* Only available in the environments with [Node.js Streams](https://nodejs.dev/learn/nodejs-streams).
*
* @see [API](https://react.dev/reference/react-dom/server/renderToPipeableStream)
*
* @param children
* @param options
*/
export function renderToPipeableStream(children: ReactNode, options?: RenderToPipeableStreamOptions): PipeableStream;
/**
* Render a React element to its initial HTML. This should only be used on the server.
* React will return an HTML string. You can use this method to generate HTML on the server
* and send the markup down on the initial request for faster page loads and to allow search
* engines to crawl your pages for SEO purposes.
*
* If you call `ReactDOMClient.hydrateRoot()` on a node that already has this server-rendered markup,
* React will preserve it and only attach event handlers, allowing you
* to have a very performant first-load experience.
*/
export function renderToString(element: ReactNode, options?: ServerOptions): string;
/**
* Similar to `renderToString`, except this doesn't create extra DOM attributes
* such as `data-reactid`, that React uses internally. This is useful if you want
* to use React as a simple static page generator, as stripping away the extra
* attributes can save lots of bytes.
*/
export function renderToStaticMarkup(element: ReactNode, options?: ServerOptions): string;
export interface RenderToReadableStreamOptions {
identifierPrefix?: string;
importMap?: ReactImportMap | undefined;
namespaceURI?: string;
nonce?: string;
bootstrapScriptContent?: string;
bootstrapScripts?: Array<string | BootstrapScriptDescriptor>;
bootstrapModules?: Array<string | BootstrapScriptDescriptor>;
/**
* Maximum length of the header content in unicode code units i.e. string.length.
* Must be a positive integer if specified.
* @default 2000
*/
headersLengthHint?: number | undefined;
progressiveChunkSize?: number;
signal?: AbortSignal;
onError?: (error: unknown, errorInfo: ErrorInfo) => string | void;
onHeaders?: ((headers: Headers) => void) | undefined;
formState?: ReactFormState | null;
}
export interface ReactDOMServerReadableStream extends ReadableStream {
allReady: Promise<void>;
}
/**
* Only available in the environments with [Web Streams](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API) (this includes browsers, Deno, and some modern edge runtimes).
*
* @see [API](https://react.dev/reference/react-dom/server/renderToReadableStream)
*/
export function renderToReadableStream(
children: ReactNode,
options?: RenderToReadableStreamOptions,
): Promise<ReactDOMServerReadableStream>;
export { ResumeOptions };
/**
* @see {@link https://react.dev/reference/react-dom/server/resume `resume`` reference documentation}
* @version 19.2
*/
export function resume(
children: React.ReactNode,
postponedState: PostponedState,
options?: ResumeOptions,
): Promise<ReactDOMServerReadableStream>;
/**
* @see {@link https://react.dev/reference/react-dom/server/resumeToPipeableStream `resumeToPipeableStream`` reference documentation}
* @version 19.2
*/
export function resumeToPipeableStream(
children: React.ReactNode,
postponedState: PostponedState,
options?: ResumeOptions,
): Promise<PipeableStream>;
export const version: string;
export as namespace ReactDOMServer;
-1
View File
@@ -1 +0,0 @@
export { renderToReadableStream, renderToStaticMarkup, renderToString, resume } from "./server";
-8
View File
@@ -1,8 +0,0 @@
export {
renderToPipeableStream,
renderToReadableStream,
renderToStaticMarkup,
renderToString,
resume,
resumeToPipeableStream,
} from "./server";
-1
View File
@@ -1 +0,0 @@
export { prerender, version } from "./static";
-153
View File
@@ -1,153 +0,0 @@
// forward declarations
declare global {
namespace NodeJS {
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface ReadableStream {}
}
/**
* Stub for https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
*/
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface AbortSignal {}
/**
* Stub for https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream
*/
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface ReadableStream<R = any> {}
/**
* Stub for https://developer.mozilla.org/en-US/docs/Web/API/Uint8Array
*/
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface Uint8Array {}
}
import { ReactNode } from "react";
import { ErrorInfo } from "./client";
export {};
declare const POSTPONED_STATE_SIGIL: unique symbol;
/**
* This is an opaque type i.e. users should not make any assumptions about its structure.
* It is JSON-serializeable to be a able to store it and retrvieve later for use with {@link https://react.dev/reference/react-dom/server/resume `resume`}.
*/
export interface PostponedState {
[POSTPONED_STATE_SIGIL]: never;
}
/**
* @see {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/script/type/importmap Import maps}
*/
// TODO: Ideally TypeScripts standard library would include this type.
// Until then we keep the prefixed one for future compatibility.
export interface ReactImportMap {
/**
* @see {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/script/type/importmap#imports `imports` reference}
*/
imports?: {
[specifier: string]: string;
} | undefined;
/**
* @see {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/script/type/importmap#integrity `integrity` reference}
*/
integrity?: {
[moduleURL: string]: string;
} | undefined;
/**
* @see {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/script/type/importmap#scopes `scopes` reference}
*/
scopes?: {
[scope: string]: {
[specifier: string]: string;
};
} | undefined;
}
export interface BootstrapScriptDescriptor {
src: string;
integrity?: string | undefined;
crossOrigin?: string | undefined;
}
export interface PrerenderOptions {
bootstrapScriptContent?: string;
bootstrapScripts?: Array<string | BootstrapScriptDescriptor>;
bootstrapModules?: Array<string | BootstrapScriptDescriptor>;
/**
* Maximum length of the header content in unicode code units i.e. string.length.
* Must be a positive integer if specified.
* @default 2000
*/
headersLengthHint?: number | undefined;
identifierPrefix?: string;
importMap?: ReactImportMap | undefined;
namespaceURI?: string;
onError?: (error: unknown, errorInfo: ErrorInfo) => string | void;
onHeaders?: (headers: Headers) => void | undefined;
progressiveChunkSize?: number;
signal?: AbortSignal;
}
export interface PrerenderResult {
postponed: null | PostponedState;
prelude: ReadableStream<Uint8Array>;
}
/**
* Only available in the environments with [Web Streams](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API) (this includes browsers, Deno, and some modern edge runtimes).
*
* @see [API](https://react.dev/reference/react-dom/static/prerender)
*/
export function prerender(
reactNode: ReactNode,
options?: PrerenderOptions,
): Promise<PrerenderResult>;
export interface PrerenderToNodeStreamResult {
prelude: NodeJS.ReadableStream;
postponed: null | PostponedState;
}
/**
* Only available in the environments with [Node.js Streams](https://nodejs.dev/learn/nodejs-streams).
*
* @see [API](https://react.dev/reference/react-dom/static/prerenderToNodeStream)
*
* @param children
* @param options
*/
export function prerenderToNodeStream(
reactNode: ReactNode,
options?: PrerenderOptions,
): Promise<PrerenderToNodeStreamResult>;
export interface ResumeOptions {
nonce?: string;
signal?: AbortSignal;
onError?: (error: unknown) => string | undefined | void;
}
/**
* @see {@link https://react.dev/reference/react-dom/static/resumeAndPrerender `resumeAndPrerender` reference documentation}
* @version 19.2
*/
export function resumeAndPrerender(
children: React.ReactNode,
postponedState: null | PostponedState,
options?: Omit<ResumeOptions, "nonce">,
): Promise<PrerenderResult>;
/**
* @see {@link https://react.dev/reference/react-dom/static/resumeAndPrerenderToNodeStream `resumeAndPrerenderToNodeStream`` reference documentation}
* @version 19.2
*/
export function resumeAndPrerenderToNodeStream(
children: React.ReactNode,
postponedState: null | PostponedState,
options?: Omit<ResumeOptions, "nonce">,
): Promise<PrerenderToNodeStreamResult>;
export const version: string;
-1
View File
@@ -1 +0,0 @@
export { prerender, resumeAndPrerender, version } from "./static";
-7
View File
@@ -1,7 +0,0 @@
export {
prerender,
prerenderToNodeStream,
resumeAndPrerender,
resumeAndPrerenderToNodeStream,
version,
} from "./static";
-7
View File
@@ -1,7 +0,0 @@
export {};
export {
/**
* @deprecated Import `act` from `react` instead.
*/ act,
} from "react";
-21
View File
@@ -1,21 +0,0 @@
MIT License
Copyright (c) Microsoft Corporation.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
-15
View File
@@ -1,15 +0,0 @@
# Installation
> `npm install --save @types/react`
# Summary
This package contains type definitions for react (https://react.dev/).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/react.
### Additional Details
* Last updated: Fri, 05 Jun 2026 20:10:10 GMT
* Dependencies: [csstype](https://npmjs.com/package/csstype)
# Credits
These definitions were written by [Asana](https://asana.com), [AssureSign](http://www.assuresign.com), [Microsoft](https://microsoft.com), [John Reilly](https://github.com/johnnyreilly), [Benoit Benezech](https://github.com/bbenezech), [Patricio Zavolinsky](https://github.com/pzavolinsky), [Eric Anderson](https://github.com/ericanderson), [Dovydas Navickas](https://github.com/DovydasNavickas), [Josh Rutherford](https://github.com/theruther4d), [Guilherme Hübner](https://github.com/guilhermehubner), [Ferdy Budhidharma](https://github.com/ferdaber), [Johann Rakotoharisoa](https://github.com/jrakotoharisoa), [Olivier Pascal](https://github.com/pascaloliv), [Martin Hochel](https://github.com/hotell), [Frank Li](https://github.com/franklixuefei), [Jessica Franco](https://github.com/Jessidhia), [Saransh Kataria](https://github.com/saranshkataria), [Kanitkorn Sujautra](https://github.com/lukyth), [Sebastian Silbermann](https://github.com/eps1lon), [Kyle Scully](https://github.com/zieka), [Cong Zhang](https://github.com/dancerphil), [Dimitri Mitropoulos](https://github.com/dimitropoulos), [JongChan Choi](https://github.com/disjukr), [Victor Magalhães](https://github.com/vhfmag), [Priyanshu Rav](https://github.com/priyanshurav), [Dmitry Semigradsky](https://github.com/Semigradsky), and [Matt Pocock](https://github.com/mattpocock).
-129
View File
@@ -1,129 +0,0 @@
/**
* These are types for things that are present in the React `canary` release channel.
*
* To load the types declared here in an actual project, there are three ways. The easiest one,
* if your `tsconfig.json` already has a `"types"` array in the `"compilerOptions"` section,
* is to add `"react/canary"` to the `"types"` array.
*
* Alternatively, a specific import syntax can to be used from a typescript file.
* This module does not exist in reality, which is why the {} is important:
*
* ```ts
* import {} from 'react/canary'
* ```
*
* It is also possible to include it through a triple-slash reference:
*
* ```ts
* /// <reference types="react/canary" />
* ```
*
* Either the import or the reference only needs to appear once, anywhere in the project.
*/
// See https://github.com/facebook/react/blob/main/packages/react/src/React.js to see how the exports are declared,
import React = require(".");
export {};
declare const UNDEFINED_VOID_ONLY: unique symbol;
type VoidOrUndefinedOnly = void | { [UNDEFINED_VOID_ONLY]: never };
type NativeSubmitEvent = SubmitEvent;
declare module "." {
export function unstable_useCacheRefresh(): () => void;
// @enableViewTransition
export interface ViewTransitionInstance {
/**
* The {@link ViewTransitionProps name} that was used in the corresponding {@link ViewTransition} component or `"auto"` if the `name` prop was omitted.
*/
name: string;
}
export type ViewTransitionClassPerType = Record<"default" | (string & {}), "none" | "auto" | (string & {})>;
export type ViewTransitionClass = ViewTransitionClassPerType | ViewTransitionClassPerType[string];
export interface ViewTransitionProps {
children?: ReactNode | undefined;
/**
* Assigns the {@link https://developer.chrome.com/blog/view-transitions-update-io24#view-transition-class `view-transition-class`} class to the underlying DOM node.
*/
default?: ViewTransitionClass | undefined;
/**
* Combined with {@link className} if this `<ViewTransition>` or its parent Component is mounted and there's no other with the same name being deleted.
* `"none"` is a special value that deactivates the view transition name under that condition.
*/
enter?: ViewTransitionClass | undefined;
/**
* Combined with {@link className} if this `<ViewTransition>` or its parent Component is unmounted and there's no other with the same name being deleted.
* `"none"` is a special value that deactivates the view transition name under that condition.
*/
exit?: ViewTransitionClass | undefined;
/**
* "auto" will automatically assign a view-transition-name to the inner DOM node.
* That way you can add a View Transition to a Component without controlling its DOM nodes styling otherwise.
*
* A difference between this and the browser's built-in view-transition-name: auto is that switching the DOM nodes within the `<ViewTransition>` component preserves the same name so this example cross-fades between the DOM nodes instead of causing an exit and enter.
* @default "auto"
*/
name?: "auto" | (string & {}) | undefined;
/**
* The `<ViewTransition>` or its parent Component is mounted and there's no other `<ViewTransition>` with the same name being deleted.
*/
onEnter?: (instance: ViewTransitionInstance, types: Array<string>) => void | (() => void);
/**
* The `<ViewTransition>` or its parent Component is unmounted and there's no other `<ViewTransition>` with the same name being deleted.
*/
onExit?: (instance: ViewTransitionInstance, types: Array<string>) => void | (() => void);
/**
* This `<ViewTransition>` is being mounted and another `<ViewTransition>` instance with the same name is being unmounted elsewhere.
*/
onShare?: (instance: ViewTransitionInstance, types: Array<string>) => void | (() => void);
/**
* The content of `<ViewTransition>` has changed either due to DOM mutations or because an inner child `<ViewTransition>` has resized.
*/
onUpdate?: (instance: ViewTransitionInstance, types: Array<string>) => void | (() => void);
ref?: Ref<ViewTransitionInstance> | undefined;
/**
* Combined with {@link className} if this `<ViewTransition>` is being mounted and another instance with the same name is being unmounted elsewhere.
* `"none"` is a special value that deactivates the view transition name under that condition.
*/
share?: ViewTransitionClass | undefined;
/**
* Combined with {@link className} if the content of this `<ViewTransition>` has changed either due to DOM mutations or because an inner child has resized.
* `"none"` is a special value that deactivates the view transition name under that condition.
*/
update?: ViewTransitionClass | undefined;
}
/**
* Opt-in for using {@link https://developer.mozilla.org/en-US/docs/Web/API/View_Transition_API View Transitions} in React.
* View Transitions only trigger for async updates like {@link startTransition}, {@link useDeferredValue}, Actions or <{@link Suspense}> revealing from fallback to content.
* Synchronous updates provide an opt-out but also guarantee that they commit immediately which View Transitions can't.
*
* @see {@link https://react.dev/reference/react/ViewTransition `<ViewTransition>` reference documentation}
*/
export const ViewTransition: ExoticComponent<ViewTransitionProps>;
/**
* @see {@link https://react.dev/reference/react/addTransitionType `addTransitionType` reference documentation}
*/
export function addTransitionType(type: string): void;
// @enableFragmentRefs
export interface FragmentInstance {}
export interface FragmentProps {
ref?: Ref<FragmentInstance> | undefined;
}
interface SubmitEvent<T = Element> extends SyntheticEvent<T, NativeSubmitEvent> {
/**
* Only available in react@canary
*/
submitter: HTMLElement | null;
}
}
-4
View File
@@ -1,4 +0,0 @@
// Not meant to be used directly
// Omitting all exports so that they don't appear in IDE autocomplete.
export {};
-184
View File
@@ -1,184 +0,0 @@
/**
* These are types for things that are present in the `experimental` builds of React but not yet
* on a stable build.
*
* Once they are promoted to stable they can just be moved to the main index file.
*
* To load the types declared here in an actual project, there are three ways. The easiest one,
* if your `tsconfig.json` already has a `"types"` array in the `"compilerOptions"` section,
* is to add `"react/experimental"` to the `"types"` array.
*
* Alternatively, a specific import syntax can to be used from a typescript file.
* This module does not exist in reality, which is why the {} is important:
*
* ```ts
* import {} from 'react/experimental'
* ```
*
* It is also possible to include it through a triple-slash reference:
*
* ```ts
* /// <reference types="react/experimental" />
* ```
*
* Either the import or the reference only needs to appear once, anywhere in the project.
*/
// See https://github.com/facebook/react/blob/master/packages/react/src/React.js to see how the exports are declared,
// and https://github.com/facebook/react/blob/master/packages/shared/ReactFeatureFlags.js to verify which APIs are
// flagged experimental or not. Experimental APIs will be tagged with `__EXPERIMENTAL__`.
//
// For the inputs of types exported as simply a fiber tag, the `beginWork` function of ReactFiberBeginWork.js
// is a good place to start looking for details; it generally calls prop validation functions or delegates
// all tasks done as part of the render phase (the concurrent part of the React update cycle).
//
// Suspense-related handling can be found in ReactFiberThrow.js.
import React = require("./canary");
export {};
declare const UNDEFINED_VOID_ONLY: unique symbol;
type VoidOrUndefinedOnly = void | { [UNDEFINED_VOID_ONLY]: never };
declare module "." {
export interface SuspenseProps {
// @enableCPUSuspense
/**
* The presence of this prop indicates that the content is computationally expensive to render.
* In other words, the tree is CPU bound and not I/O bound (e.g. due to fetching data).
* @see {@link https://github.com/facebook/react/pull/19936}
*/
defer?: boolean | undefined;
}
export type SuspenseListRevealOrder = "forwards" | "backwards" | "together" | "independent";
export type SuspenseListTailMode = "collapsed" | "hidden" | "visible";
export interface SuspenseListCommonProps {
}
interface DirectionalSuspenseListProps extends SuspenseListCommonProps {
/**
* Note that SuspenseList require more than one child;
* it is a runtime warning to provide only a single child.
*
* It does, however, allow those children to be wrapped inside a single
* level of `<React.Fragment>`.
*/
children: Iterable<ReactElement> | AsyncIterable<ReactElement>;
/**
* Defines the order in which the `SuspenseList` children should be revealed.
* @default "forwards"
*/
revealOrder?: "forwards" | "backwards" | "unstable_legacy-backwards" | undefined;
/**
* Dictates how unloaded items in a SuspenseList is shown.
*
* - `collapsed` shows only the next fallback in the list.
* - `hidden` doesn't show any unloaded items.
* - `visible` shows all fallbacks in the list.
*
* @default "hidden"
*/
tail?: SuspenseListTailMode | undefined;
}
interface NonDirectionalSuspenseListProps extends SuspenseListCommonProps {
children: ReactNode;
/**
* Defines the order in which the `SuspenseList` children should be revealed.
*/
revealOrder: Exclude<SuspenseListRevealOrder, DirectionalSuspenseListProps["revealOrder"]>;
/**
* The tail property is invalid when not using the `forwards` or `backwards` reveal orders.
*/
tail?: never;
}
export type SuspenseListProps = DirectionalSuspenseListProps | NonDirectionalSuspenseListProps;
/**
* `SuspenseList` helps coordinate many components that can suspend by orchestrating the order
* in which these components are revealed to the user.
*
* When multiple components need to fetch data, this data may arrive in an unpredictable order.
* However, if you wrap these items in a `SuspenseList`, React will not show an item in the list
* until previous items have been displayed (this behavior is adjustable).
*
* @see {@link https://reactjs.org/docs/concurrent-mode-reference.html#suspenselist}
* @see {@link https://reactjs.org/docs/concurrent-mode-patterns.html#suspenselist}
*/
export const unstable_SuspenseList: ExoticComponent<SuspenseListProps>;
type Reference = object;
type TaintableUniqueValue = string | bigint | ArrayBufferView;
function experimental_taintUniqueValue(
message: string | undefined,
lifetime: Reference,
value: TaintableUniqueValue,
): void;
function experimental_taintObjectReference(message: string | undefined, object: Reference): void;
// @enableGestureTransition
// Implemented by the specific renderer e.g. `react-dom`.
// Keep in mind that augmented interfaces merge their JSDoc so if you put
// JSDoc here and in the renderer, the IDE will display both.
export interface GestureProvider {}
export interface GestureOptions {
rangeStart?: number | undefined;
rangeEnd?: number | undefined;
}
export type GestureOptionsRequired = {
[P in keyof GestureOptions]-?: NonNullable<GestureOptions[P]>;
};
/** */
export function unstable_startGestureTransition(
provider: GestureProvider,
scope: () => void,
options?: GestureOptions,
): () => void;
interface ViewTransitionProps {
onGestureEnter?: (
timeline: GestureProvider,
options: GestureOptionsRequired,
instance: ViewTransitionInstance,
types: Array<string>,
) => void | (() => void);
onGestureExit?: (
timeline: GestureProvider,
options: GestureOptionsRequired,
instance: ViewTransitionInstance,
types: Array<string>,
) => void | (() => void);
onGestureShare?: (
timeline: GestureProvider,
options: GestureOptionsRequired,
instance: ViewTransitionInstance,
types: Array<string>,
) => void | (() => void);
onGestureUpdate?: (
timeline: GestureProvider,
options: GestureOptionsRequired,
instance: ViewTransitionInstance,
types: Array<string>,
) => void | (() => void);
}
// @enableSrcObject
interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_IMG_SRC_TYPES {
srcObject: Blob;
}
interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_MEDIA_SRC_TYPES {
srcObject: Blob | MediaSource | MediaStream;
}
// @enableOptimisticKey
export const optimisticKey: unique symbol;
interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_KEY_TYPES {
optimisticKey: typeof optimisticKey;
}
}
-166
View File
@@ -1,166 +0,0 @@
/*
React projects that don't include the DOM library need these interfaces to compile.
React Native applications use React, but there is no DOM available. The JavaScript runtime
is ES6/ES2015 only. These definitions allow such projects to compile with only `--lib ES6`.
Warning: all of these interfaces are empty. If you want type definitions for various properties
(such as HTMLInputElement.prototype.value), you need to add `--lib DOM` (via command line or tsconfig.json).
*/
interface Event {}
interface AnimationEvent extends Event {}
interface ClipboardEvent extends Event {}
interface CompositionEvent extends Event {}
interface DragEvent extends Event {}
interface FocusEvent extends Event {}
interface InputEvent extends Event {}
interface KeyboardEvent extends Event {}
interface MouseEvent extends Event {}
interface TouchEvent extends Event {}
interface PointerEvent extends Event {}
interface SubmitEvent extends Event {}
interface ToggleEvent extends Event {}
interface TransitionEvent extends Event {}
interface UIEvent extends Event {}
interface WheelEvent extends Event {}
interface EventTarget {}
interface Document {}
interface DataTransfer {}
interface StyleMedia {}
interface Element {}
interface DocumentFragment {}
interface HTMLElement extends Element {}
interface HTMLAnchorElement extends HTMLElement {}
interface HTMLAreaElement extends HTMLElement {}
interface HTMLAudioElement extends HTMLElement {}
interface HTMLBaseElement extends HTMLElement {}
interface HTMLBodyElement extends HTMLElement {}
interface HTMLBRElement extends HTMLElement {}
interface HTMLButtonElement extends HTMLElement {}
interface HTMLCanvasElement extends HTMLElement {}
interface HTMLDataElement extends HTMLElement {}
interface HTMLDataListElement extends HTMLElement {}
interface HTMLDetailsElement extends HTMLElement {}
interface HTMLDialogElement extends HTMLElement {}
interface HTMLDivElement extends HTMLElement {}
interface HTMLDListElement extends HTMLElement {}
interface HTMLEmbedElement extends HTMLElement {}
interface HTMLFieldSetElement extends HTMLElement {}
interface HTMLFormElement extends HTMLElement {}
interface HTMLHeadingElement extends HTMLElement {}
interface HTMLHeadElement extends HTMLElement {}
interface HTMLHRElement extends HTMLElement {}
interface HTMLHtmlElement extends HTMLElement {}
interface HTMLIFrameElement extends HTMLElement {}
interface HTMLImageElement extends HTMLElement {}
interface HTMLInputElement extends HTMLElement {}
interface HTMLModElement extends HTMLElement {}
interface HTMLLabelElement extends HTMLElement {}
interface HTMLLegendElement extends HTMLElement {}
interface HTMLLIElement extends HTMLElement {}
interface HTMLLinkElement extends HTMLElement {}
interface HTMLMapElement extends HTMLElement {}
interface HTMLMetaElement extends HTMLElement {}
interface HTMLMeterElement extends HTMLElement {}
interface HTMLObjectElement extends HTMLElement {}
interface HTMLOListElement extends HTMLElement {}
interface HTMLOptGroupElement extends HTMLElement {}
interface HTMLOptionElement extends HTMLElement {}
interface HTMLOutputElement extends HTMLElement {}
interface HTMLParagraphElement extends HTMLElement {}
interface HTMLParamElement extends HTMLElement {}
interface HTMLPreElement extends HTMLElement {}
interface HTMLProgressElement extends HTMLElement {}
interface HTMLQuoteElement extends HTMLElement {}
interface HTMLSlotElement extends HTMLElement {}
interface HTMLScriptElement extends HTMLElement {}
interface HTMLSelectElement extends HTMLElement {}
interface HTMLSourceElement extends HTMLElement {}
interface HTMLSpanElement extends HTMLElement {}
interface HTMLStyleElement extends HTMLElement {}
interface HTMLTableElement extends HTMLElement {}
interface HTMLTableColElement extends HTMLElement {}
interface HTMLTableDataCellElement extends HTMLElement {}
interface HTMLTableHeaderCellElement extends HTMLElement {}
interface HTMLTableRowElement extends HTMLElement {}
interface HTMLTableSectionElement extends HTMLElement {}
interface HTMLTemplateElement extends HTMLElement {}
interface HTMLTextAreaElement extends HTMLElement {}
interface HTMLTimeElement extends HTMLElement {}
interface HTMLTitleElement extends HTMLElement {}
interface HTMLTrackElement extends HTMLElement {}
interface HTMLUListElement extends HTMLElement {}
interface HTMLVideoElement extends HTMLElement {}
interface HTMLWebViewElement extends HTMLElement {}
interface SVGElement extends Element {}
interface SVGSVGElement extends SVGElement {}
interface SVGCircleElement extends SVGElement {}
interface SVGClipPathElement extends SVGElement {}
interface SVGDefsElement extends SVGElement {}
interface SVGDescElement extends SVGElement {}
interface SVGEllipseElement extends SVGElement {}
interface SVGFEBlendElement extends SVGElement {}
interface SVGFEColorMatrixElement extends SVGElement {}
interface SVGFEComponentTransferElement extends SVGElement {}
interface SVGFECompositeElement extends SVGElement {}
interface SVGFEConvolveMatrixElement extends SVGElement {}
interface SVGFEDiffuseLightingElement extends SVGElement {}
interface SVGFEDisplacementMapElement extends SVGElement {}
interface SVGFEDistantLightElement extends SVGElement {}
interface SVGFEDropShadowElement extends SVGElement {}
interface SVGFEFloodElement extends SVGElement {}
interface SVGFEFuncAElement extends SVGElement {}
interface SVGFEFuncBElement extends SVGElement {}
interface SVGFEFuncGElement extends SVGElement {}
interface SVGFEFuncRElement extends SVGElement {}
interface SVGFEGaussianBlurElement extends SVGElement {}
interface SVGFEImageElement extends SVGElement {}
interface SVGFEMergeElement extends SVGElement {}
interface SVGFEMergeNodeElement extends SVGElement {}
interface SVGFEMorphologyElement extends SVGElement {}
interface SVGFEOffsetElement extends SVGElement {}
interface SVGFEPointLightElement extends SVGElement {}
interface SVGFESpecularLightingElement extends SVGElement {}
interface SVGFESpotLightElement extends SVGElement {}
interface SVGFETileElement extends SVGElement {}
interface SVGFETurbulenceElement extends SVGElement {}
interface SVGFilterElement extends SVGElement {}
interface SVGForeignObjectElement extends SVGElement {}
interface SVGGElement extends SVGElement {}
interface SVGImageElement extends SVGElement {}
interface SVGLineElement extends SVGElement {}
interface SVGLinearGradientElement extends SVGElement {}
interface SVGMarkerElement extends SVGElement {}
interface SVGMaskElement extends SVGElement {}
interface SVGMetadataElement extends SVGElement {}
interface SVGPathElement extends SVGElement {}
interface SVGPatternElement extends SVGElement {}
interface SVGPolygonElement extends SVGElement {}
interface SVGPolylineElement extends SVGElement {}
interface SVGRadialGradientElement extends SVGElement {}
interface SVGRectElement extends SVGElement {}
interface SVGSetElement extends SVGElement {}
interface SVGStopElement extends SVGElement {}
interface SVGSwitchElement extends SVGElement {}
interface SVGSymbolElement extends SVGElement {}
interface SVGTextElement extends SVGElement {}
interface SVGTextPathElement extends SVGElement {}
interface SVGTSpanElement extends SVGElement {}
interface SVGUseElement extends SVGElement {}
interface SVGViewElement extends SVGElement {}
interface FormData {}
interface Text {}
interface TouchList {}
interface WebGLRenderingContext {}
interface WebGL2RenderingContext {}
interface TrustedHTML {}
interface Blob {}
interface MediaStream {}
interface MediaSource {}
-4369
View File
File diff suppressed because it is too large Load Diff
-33
View File
@@ -1,33 +0,0 @@
import * as React from "./";
export { Fragment, JSX } from "./";
export interface JSXSource {
/**
* The source file where the element originates from.
*/
fileName?: string | undefined;
/**
* The line number where the element was created.
*/
lineNumber?: number | undefined;
/**
* The column number where the element was created.
*/
columnNumber?: number | undefined;
}
/**
* Create a React element.
*
* You should not use this function directly. Use JSX and a transpiler instead.
*/
export function jsxDEV(
type: React.ElementType,
props: unknown,
key: React.Key | undefined,
isStatic: boolean,
source?: JSXSource,
self?: unknown,
): React.ReactElement;
-24
View File
@@ -1,24 +0,0 @@
import * as React from "./";
export { Fragment, JSX } from "./";
/**
* Create a React element.
*
* You should not use this function directly. Use JSX and a transpiler instead.
*/
export function jsx(
type: React.ElementType,
props: unknown,
key?: React.Key,
): React.ReactElement;
/**
* Create a React element.
*
* You should not use this function directly. Use JSX and a transpiler instead.
*/
export function jsxs(
type: React.ElementType,
props: unknown,
key?: React.Key,
): React.ReactElement;
-210
View File
@@ -1,210 +0,0 @@
{
"name": "@types/react",
"version": "19.2.17",
"description": "TypeScript definitions for react",
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/react",
"license": "MIT",
"contributors": [
{
"name": "Asana",
"url": "https://asana.com"
},
{
"name": "AssureSign",
"url": "http://www.assuresign.com"
},
{
"name": "Microsoft",
"url": "https://microsoft.com"
},
{
"name": "John Reilly",
"githubUsername": "johnnyreilly",
"url": "https://github.com/johnnyreilly"
},
{
"name": "Benoit Benezech",
"githubUsername": "bbenezech",
"url": "https://github.com/bbenezech"
},
{
"name": "Patricio Zavolinsky",
"githubUsername": "pzavolinsky",
"url": "https://github.com/pzavolinsky"
},
{
"name": "Eric Anderson",
"githubUsername": "ericanderson",
"url": "https://github.com/ericanderson"
},
{
"name": "Dovydas Navickas",
"githubUsername": "DovydasNavickas",
"url": "https://github.com/DovydasNavickas"
},
{
"name": "Josh Rutherford",
"githubUsername": "theruther4d",
"url": "https://github.com/theruther4d"
},
{
"name": "Guilherme Hübner",
"githubUsername": "guilhermehubner",
"url": "https://github.com/guilhermehubner"
},
{
"name": "Ferdy Budhidharma",
"githubUsername": "ferdaber",
"url": "https://github.com/ferdaber"
},
{
"name": "Johann Rakotoharisoa",
"githubUsername": "jrakotoharisoa",
"url": "https://github.com/jrakotoharisoa"
},
{
"name": "Olivier Pascal",
"githubUsername": "pascaloliv",
"url": "https://github.com/pascaloliv"
},
{
"name": "Martin Hochel",
"githubUsername": "hotell",
"url": "https://github.com/hotell"
},
{
"name": "Frank Li",
"githubUsername": "franklixuefei",
"url": "https://github.com/franklixuefei"
},
{
"name": "Jessica Franco",
"githubUsername": "Jessidhia",
"url": "https://github.com/Jessidhia"
},
{
"name": "Saransh Kataria",
"githubUsername": "saranshkataria",
"url": "https://github.com/saranshkataria"
},
{
"name": "Kanitkorn Sujautra",
"githubUsername": "lukyth",
"url": "https://github.com/lukyth"
},
{
"name": "Sebastian Silbermann",
"githubUsername": "eps1lon",
"url": "https://github.com/eps1lon"
},
{
"name": "Kyle Scully",
"githubUsername": "zieka",
"url": "https://github.com/zieka"
},
{
"name": "Cong Zhang",
"githubUsername": "dancerphil",
"url": "https://github.com/dancerphil"
},
{
"name": "Dimitri Mitropoulos",
"githubUsername": "dimitropoulos",
"url": "https://github.com/dimitropoulos"
},
{
"name": "JongChan Choi",
"githubUsername": "disjukr",
"url": "https://github.com/disjukr"
},
{
"name": "Victor Magalhães",
"githubUsername": "vhfmag",
"url": "https://github.com/vhfmag"
},
{
"name": "Priyanshu Rav",
"githubUsername": "priyanshurav",
"url": "https://github.com/priyanshurav"
},
{
"name": "Dmitry Semigradsky",
"githubUsername": "Semigradsky",
"url": "https://github.com/Semigradsky"
},
{
"name": "Matt Pocock",
"githubUsername": "mattpocock",
"url": "https://github.com/mattpocock"
}
],
"main": "",
"types": "index.d.ts",
"typesVersions": {
"<=5.0": {
"*": [
"ts5.0/*"
]
}
},
"exports": {
".": {
"types@<=5.0": {
"default": "./ts5.0/index.d.ts"
},
"types": {
"default": "./index.d.ts"
}
},
"./canary": {
"types@<=5.0": {
"default": "./ts5.0/canary.d.ts"
},
"types": {
"default": "./canary.d.ts"
}
},
"./compiler-runtime": {
"types": {
"default": "./compiler-runtime.d.ts"
}
},
"./experimental": {
"types@<=5.0": {
"default": "./ts5.0/experimental.d.ts"
},
"types": {
"default": "./experimental.d.ts"
}
},
"./jsx-runtime": {
"types@<=5.0": {
"default": "./ts5.0/jsx-runtime.d.ts"
},
"types": {
"default": "./jsx-runtime.d.ts"
}
},
"./jsx-dev-runtime": {
"types@<=5.0": {
"default": "./ts5.0/jsx-dev-runtime.d.ts"
},
"types": {
"default": "./jsx-dev-runtime.d.ts"
}
},
"./package.json": "./package.json"
},
"repository": {
"type": "git",
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
"directory": "types/react"
},
"scripts": {},
"dependencies": {
"csstype": "^3.2.2"
},
"peerDependencies": {},
"typesPublisherContentHash": "f6d087e89b6a483b6ea2519d4f16498227ceb3260f6a6414fed750badc869721",
"typeScriptVersion": "5.3"
}
-129
View File
@@ -1,129 +0,0 @@
/**
* These are types for things that are present in the React `canary` release channel.
*
* To load the types declared here in an actual project, there are three ways. The easiest one,
* if your `tsconfig.json` already has a `"types"` array in the `"compilerOptions"` section,
* is to add `"react/canary"` to the `"types"` array.
*
* Alternatively, a specific import syntax can to be used from a typescript file.
* This module does not exist in reality, which is why the {} is important:
*
* ```ts
* import {} from 'react/canary'
* ```
*
* It is also possible to include it through a triple-slash reference:
*
* ```ts
* /// <reference types="react/canary" />
* ```
*
* Either the import or the reference only needs to appear once, anywhere in the project.
*/
// See https://github.com/facebook/react/blob/main/packages/react/src/React.js to see how the exports are declared,
import React = require(".");
export {};
declare const UNDEFINED_VOID_ONLY: unique symbol;
type VoidOrUndefinedOnly = void | { [UNDEFINED_VOID_ONLY]: never };
type NativeSubmitEvent = SubmitEvent;
declare module "." {
export function unstable_useCacheRefresh(): () => void;
// @enableViewTransition
export interface ViewTransitionInstance {
/**
* The {@link ViewTransitionProps name} that was used in the corresponding {@link ViewTransition} component or `"auto"` if the `name` prop was omitted.
*/
name: string;
}
export type ViewTransitionClassPerType = Record<"default" | (string & {}), "none" | "auto" | (string & {})>;
export type ViewTransitionClass = ViewTransitionClassPerType | ViewTransitionClassPerType[string];
export interface ViewTransitionProps {
children?: ReactNode | undefined;
/**
* Assigns the {@link https://developer.chrome.com/blog/view-transitions-update-io24#view-transition-class `view-transition-class`} class to the underlying DOM node.
*/
default?: ViewTransitionClass | undefined;
/**
* Combined with {@link className} if this `<ViewTransition>` or its parent Component is mounted and there's no other with the same name being deleted.
* `"none"` is a special value that deactivates the view transition name under that condition.
*/
enter?: ViewTransitionClass | undefined;
/**
* Combined with {@link className} if this `<ViewTransition>` or its parent Component is unmounted and there's no other with the same name being deleted.
* `"none"` is a special value that deactivates the view transition name under that condition.
*/
exit?: ViewTransitionClass | undefined;
/**
* "auto" will automatically assign a view-transition-name to the inner DOM node.
* That way you can add a View Transition to a Component without controlling its DOM nodes styling otherwise.
*
* A difference between this and the browser's built-in view-transition-name: auto is that switching the DOM nodes within the `<ViewTransition>` component preserves the same name so this example cross-fades between the DOM nodes instead of causing an exit and enter.
* @default "auto"
*/
name?: "auto" | (string & {}) | undefined;
/**
* The `<ViewTransition>` or its parent Component is mounted and there's no other `<ViewTransition>` with the same name being deleted.
*/
onEnter?: (instance: ViewTransitionInstance, types: Array<string>) => void | (() => void);
/**
* The `<ViewTransition>` or its parent Component is unmounted and there's no other `<ViewTransition>` with the same name being deleted.
*/
onExit?: (instance: ViewTransitionInstance, types: Array<string>) => void | (() => void);
/**
* This `<ViewTransition>` is being mounted and another `<ViewTransition>` instance with the same name is being unmounted elsewhere.
*/
onShare?: (instance: ViewTransitionInstance, types: Array<string>) => void | (() => void);
/**
* The content of `<ViewTransition>` has changed either due to DOM mutations or because an inner child `<ViewTransition>` has resized.
*/
onUpdate?: (instance: ViewTransitionInstance, types: Array<string>) => void | (() => void);
ref?: Ref<ViewTransitionInstance> | undefined;
/**
* Combined with {@link className} if this `<ViewTransition>` is being mounted and another instance with the same name is being unmounted elsewhere.
* `"none"` is a special value that deactivates the view transition name under that condition.
*/
share?: ViewTransitionClass | undefined;
/**
* Combined with {@link className} if the content of this `<ViewTransition>` has changed either due to DOM mutations or because an inner child has resized.
* `"none"` is a special value that deactivates the view transition name under that condition.
*/
update?: ViewTransitionClass | undefined;
}
/**
* Opt-in for using {@link https://developer.mozilla.org/en-US/docs/Web/API/View_Transition_API View Transitions} in React.
* View Transitions only trigger for async updates like {@link startTransition}, {@link useDeferredValue}, Actions or <{@link Suspense}> revealing from fallback to content.
* Synchronous updates provide an opt-out but also guarantee that they commit immediately which View Transitions can't.
*
* @see {@link https://react.dev/reference/react/ViewTransition `<ViewTransition>` reference documentation}
*/
export const ViewTransition: ExoticComponent<ViewTransitionProps>;
/**
* @see {@link https://react.dev/reference/react/addTransitionType `addTransitionType` reference documentation}
*/
export function addTransitionType(type: string): void;
// @enableFragmentRefs
export interface FragmentInstance {}
export interface FragmentProps {
ref?: Ref<FragmentInstance> | undefined;
}
interface SubmitEvent<T = Element> extends SyntheticEvent<T, NativeSubmitEvent> {
/**
* Only available in react@canary
*/
submitter: HTMLElement | null;
}
}
-184
View File
@@ -1,184 +0,0 @@
/**
* These are types for things that are present in the `experimental` builds of React but not yet
* on a stable build.
*
* Once they are promoted to stable they can just be moved to the main index file.
*
* To load the types declared here in an actual project, there are three ways. The easiest one,
* if your `tsconfig.json` already has a `"types"` array in the `"compilerOptions"` section,
* is to add `"react/experimental"` to the `"types"` array.
*
* Alternatively, a specific import syntax can to be used from a typescript file.
* This module does not exist in reality, which is why the {} is important:
*
* ```ts
* import {} from 'react/experimental'
* ```
*
* It is also possible to include it through a triple-slash reference:
*
* ```ts
* /// <reference types="react/experimental" />
* ```
*
* Either the import or the reference only needs to appear once, anywhere in the project.
*/
// See https://github.com/facebook/react/blob/master/packages/react/src/React.js to see how the exports are declared,
// and https://github.com/facebook/react/blob/master/packages/shared/ReactFeatureFlags.js to verify which APIs are
// flagged experimental or not. Experimental APIs will be tagged with `__EXPERIMENTAL__`.
//
// For the inputs of types exported as simply a fiber tag, the `beginWork` function of ReactFiberBeginWork.js
// is a good place to start looking for details; it generally calls prop validation functions or delegates
// all tasks done as part of the render phase (the concurrent part of the React update cycle).
//
// Suspense-related handling can be found in ReactFiberThrow.js.
import React = require("./canary");
export {};
declare const UNDEFINED_VOID_ONLY: unique symbol;
type VoidOrUndefinedOnly = void | { [UNDEFINED_VOID_ONLY]: never };
declare module "." {
export interface SuspenseProps {
// @enableCPUSuspense
/**
* The presence of this prop indicates that the content is computationally expensive to render.
* In other words, the tree is CPU bound and not I/O bound (e.g. due to fetching data).
* @see {@link https://github.com/facebook/react/pull/19936}
*/
defer?: boolean | undefined;
}
export type SuspenseListRevealOrder = "forwards" | "backwards" | "together" | "independent";
export type SuspenseListTailMode = "collapsed" | "hidden" | "visible";
export interface SuspenseListCommonProps {
}
interface DirectionalSuspenseListProps extends SuspenseListCommonProps {
/**
* Note that SuspenseList require more than one child;
* it is a runtime warning to provide only a single child.
*
* It does, however, allow those children to be wrapped inside a single
* level of `<React.Fragment>`.
*/
children: Iterable<ReactElement> | AsyncIterable<ReactElement>;
/**
* Defines the order in which the `SuspenseList` children should be revealed.
* @default "forwards"
*/
revealOrder?: "forwards" | "backwards" | "unstable_legacy-backwards" | undefined;
/**
* Dictates how unloaded items in a SuspenseList is shown.
*
* - `collapsed` shows only the next fallback in the list.
* - `hidden` doesn't show any unloaded items.
* - `visible` shows all fallbacks in the list.
*
* @default "hidden"
*/
tail?: SuspenseListTailMode | undefined;
}
interface NonDirectionalSuspenseListProps extends SuspenseListCommonProps {
children: ReactNode;
/**
* Defines the order in which the `SuspenseList` children should be revealed.
*/
revealOrder: Exclude<SuspenseListRevealOrder, DirectionalSuspenseListProps["revealOrder"]>;
/**
* The tail property is invalid when not using the `forwards` or `backwards` reveal orders.
*/
tail?: never;
}
export type SuspenseListProps = DirectionalSuspenseListProps | NonDirectionalSuspenseListProps;
/**
* `SuspenseList` helps coordinate many components that can suspend by orchestrating the order
* in which these components are revealed to the user.
*
* When multiple components need to fetch data, this data may arrive in an unpredictable order.
* However, if you wrap these items in a `SuspenseList`, React will not show an item in the list
* until previous items have been displayed (this behavior is adjustable).
*
* @see {@link https://reactjs.org/docs/concurrent-mode-reference.html#suspenselist}
* @see {@link https://reactjs.org/docs/concurrent-mode-patterns.html#suspenselist}
*/
export const unstable_SuspenseList: ExoticComponent<SuspenseListProps>;
type Reference = object;
type TaintableUniqueValue = string | bigint | ArrayBufferView;
function experimental_taintUniqueValue(
message: string | undefined,
lifetime: Reference,
value: TaintableUniqueValue,
): void;
function experimental_taintObjectReference(message: string | undefined, object: Reference): void;
// @enableGestureTransition
// Implemented by the specific renderer e.g. `react-dom`.
// Keep in mind that augmented interfaces merge their JSDoc so if you put
// JSDoc here and in the renderer, the IDE will display both.
export interface GestureProvider {}
export interface GestureOptions {
rangeStart?: number | undefined;
rangeEnd?: number | undefined;
}
export type GestureOptionsRequired = {
[P in keyof GestureOptions]-?: NonNullable<GestureOptions[P]>;
};
/** */
export function unstable_startGestureTransition(
provider: GestureProvider,
scope: () => void,
options?: GestureOptions,
): () => void;
interface ViewTransitionProps {
onGestureEnter?: (
timeline: GestureProvider,
options: GestureOptionsRequired,
instance: ViewTransitionInstance,
types: Array<string>,
) => void | (() => void);
onGestureExit?: (
timeline: GestureProvider,
options: GestureOptionsRequired,
instance: ViewTransitionInstance,
types: Array<string>,
) => void | (() => void);
onGestureShare?: (
timeline: GestureProvider,
options: GestureOptionsRequired,
instance: ViewTransitionInstance,
types: Array<string>,
) => void | (() => void);
onGestureUpdate?: (
timeline: GestureProvider,
options: GestureOptionsRequired,
instance: ViewTransitionInstance,
types: Array<string>,
) => void | (() => void);
}
// @enableSrcObject
interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_IMG_SRC_TYPES {
srcObject: Blob;
}
interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_MEDIA_SRC_TYPES {
srcObject: Blob | MediaSource | MediaStream;
}
// @enableOptimisticKey
export const optimisticKey: unique symbol;
interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_KEY_TYPES {
optimisticKey: typeof optimisticKey;
}
}
-166
View File
@@ -1,166 +0,0 @@
/*
React projects that don't include the DOM library need these interfaces to compile.
React Native applications use React, but there is no DOM available. The JavaScript runtime
is ES6/ES2015 only. These definitions allow such projects to compile with only `--lib ES6`.
Warning: all of these interfaces are empty. If you want type definitions for various properties
(such as HTMLInputElement.prototype.value), you need to add `--lib DOM` (via command line or tsconfig.json).
*/
interface Event {}
interface AnimationEvent extends Event {}
interface ClipboardEvent extends Event {}
interface CompositionEvent extends Event {}
interface DragEvent extends Event {}
interface FocusEvent extends Event {}
interface InputEvent extends Event {}
interface KeyboardEvent extends Event {}
interface MouseEvent extends Event {}
interface TouchEvent extends Event {}
interface PointerEvent extends Event {}
interface SubmitEvent extends Event {}
interface ToggleEvent extends Event {}
interface TransitionEvent extends Event {}
interface UIEvent extends Event {}
interface WheelEvent extends Event {}
interface EventTarget {}
interface Document {}
interface DataTransfer {}
interface StyleMedia {}
interface Element {}
interface DocumentFragment {}
interface HTMLElement extends Element {}
interface HTMLAnchorElement extends HTMLElement {}
interface HTMLAreaElement extends HTMLElement {}
interface HTMLAudioElement extends HTMLElement {}
interface HTMLBaseElement extends HTMLElement {}
interface HTMLBodyElement extends HTMLElement {}
interface HTMLBRElement extends HTMLElement {}
interface HTMLButtonElement extends HTMLElement {}
interface HTMLCanvasElement extends HTMLElement {}
interface HTMLDataElement extends HTMLElement {}
interface HTMLDataListElement extends HTMLElement {}
interface HTMLDetailsElement extends HTMLElement {}
interface HTMLDialogElement extends HTMLElement {}
interface HTMLDivElement extends HTMLElement {}
interface HTMLDListElement extends HTMLElement {}
interface HTMLEmbedElement extends HTMLElement {}
interface HTMLFieldSetElement extends HTMLElement {}
interface HTMLFormElement extends HTMLElement {}
interface HTMLHeadingElement extends HTMLElement {}
interface HTMLHeadElement extends HTMLElement {}
interface HTMLHRElement extends HTMLElement {}
interface HTMLHtmlElement extends HTMLElement {}
interface HTMLIFrameElement extends HTMLElement {}
interface HTMLImageElement extends HTMLElement {}
interface HTMLInputElement extends HTMLElement {}
interface HTMLModElement extends HTMLElement {}
interface HTMLLabelElement extends HTMLElement {}
interface HTMLLegendElement extends HTMLElement {}
interface HTMLLIElement extends HTMLElement {}
interface HTMLLinkElement extends HTMLElement {}
interface HTMLMapElement extends HTMLElement {}
interface HTMLMetaElement extends HTMLElement {}
interface HTMLMeterElement extends HTMLElement {}
interface HTMLObjectElement extends HTMLElement {}
interface HTMLOListElement extends HTMLElement {}
interface HTMLOptGroupElement extends HTMLElement {}
interface HTMLOptionElement extends HTMLElement {}
interface HTMLOutputElement extends HTMLElement {}
interface HTMLParagraphElement extends HTMLElement {}
interface HTMLParamElement extends HTMLElement {}
interface HTMLPreElement extends HTMLElement {}
interface HTMLProgressElement extends HTMLElement {}
interface HTMLQuoteElement extends HTMLElement {}
interface HTMLSlotElement extends HTMLElement {}
interface HTMLScriptElement extends HTMLElement {}
interface HTMLSelectElement extends HTMLElement {}
interface HTMLSourceElement extends HTMLElement {}
interface HTMLSpanElement extends HTMLElement {}
interface HTMLStyleElement extends HTMLElement {}
interface HTMLTableElement extends HTMLElement {}
interface HTMLTableColElement extends HTMLElement {}
interface HTMLTableDataCellElement extends HTMLElement {}
interface HTMLTableHeaderCellElement extends HTMLElement {}
interface HTMLTableRowElement extends HTMLElement {}
interface HTMLTableSectionElement extends HTMLElement {}
interface HTMLTemplateElement extends HTMLElement {}
interface HTMLTextAreaElement extends HTMLElement {}
interface HTMLTimeElement extends HTMLElement {}
interface HTMLTitleElement extends HTMLElement {}
interface HTMLTrackElement extends HTMLElement {}
interface HTMLUListElement extends HTMLElement {}
interface HTMLVideoElement extends HTMLElement {}
interface HTMLWebViewElement extends HTMLElement {}
interface SVGElement extends Element {}
interface SVGSVGElement extends SVGElement {}
interface SVGCircleElement extends SVGElement {}
interface SVGClipPathElement extends SVGElement {}
interface SVGDefsElement extends SVGElement {}
interface SVGDescElement extends SVGElement {}
interface SVGEllipseElement extends SVGElement {}
interface SVGFEBlendElement extends SVGElement {}
interface SVGFEColorMatrixElement extends SVGElement {}
interface SVGFEComponentTransferElement extends SVGElement {}
interface SVGFECompositeElement extends SVGElement {}
interface SVGFEConvolveMatrixElement extends SVGElement {}
interface SVGFEDiffuseLightingElement extends SVGElement {}
interface SVGFEDisplacementMapElement extends SVGElement {}
interface SVGFEDistantLightElement extends SVGElement {}
interface SVGFEDropShadowElement extends SVGElement {}
interface SVGFEFloodElement extends SVGElement {}
interface SVGFEFuncAElement extends SVGElement {}
interface SVGFEFuncBElement extends SVGElement {}
interface SVGFEFuncGElement extends SVGElement {}
interface SVGFEFuncRElement extends SVGElement {}
interface SVGFEGaussianBlurElement extends SVGElement {}
interface SVGFEImageElement extends SVGElement {}
interface SVGFEMergeElement extends SVGElement {}
interface SVGFEMergeNodeElement extends SVGElement {}
interface SVGFEMorphologyElement extends SVGElement {}
interface SVGFEOffsetElement extends SVGElement {}
interface SVGFEPointLightElement extends SVGElement {}
interface SVGFESpecularLightingElement extends SVGElement {}
interface SVGFESpotLightElement extends SVGElement {}
interface SVGFETileElement extends SVGElement {}
interface SVGFETurbulenceElement extends SVGElement {}
interface SVGFilterElement extends SVGElement {}
interface SVGForeignObjectElement extends SVGElement {}
interface SVGGElement extends SVGElement {}
interface SVGImageElement extends SVGElement {}
interface SVGLineElement extends SVGElement {}
interface SVGLinearGradientElement extends SVGElement {}
interface SVGMarkerElement extends SVGElement {}
interface SVGMaskElement extends SVGElement {}
interface SVGMetadataElement extends SVGElement {}
interface SVGPathElement extends SVGElement {}
interface SVGPatternElement extends SVGElement {}
interface SVGPolygonElement extends SVGElement {}
interface SVGPolylineElement extends SVGElement {}
interface SVGRadialGradientElement extends SVGElement {}
interface SVGRectElement extends SVGElement {}
interface SVGSetElement extends SVGElement {}
interface SVGStopElement extends SVGElement {}
interface SVGSwitchElement extends SVGElement {}
interface SVGSymbolElement extends SVGElement {}
interface SVGTextElement extends SVGElement {}
interface SVGTextPathElement extends SVGElement {}
interface SVGTSpanElement extends SVGElement {}
interface SVGUseElement extends SVGElement {}
interface SVGViewElement extends SVGElement {}
interface FormData {}
interface Text {}
interface TouchList {}
interface WebGLRenderingContext {}
interface WebGL2RenderingContext {}
interface TrustedHTML {}
interface Blob {}
interface MediaStream {}
interface MediaSource {}
-4356
View File
File diff suppressed because it is too large Load Diff
-33
View File
@@ -1,33 +0,0 @@
import * as React from "./";
export { Fragment, JSX } from "./";
export interface JSXSource {
/**
* The source file where the element originates from.
*/
fileName?: string | undefined;
/**
* The line number where the element was created.
*/
lineNumber?: number | undefined;
/**
* The column number where the element was created.
*/
columnNumber?: number | undefined;
}
/**
* Create a React element.
*
* You should not use this function directly. Use JSX and a transpiler instead.
*/
export function jsxDEV(
type: React.ElementType,
props: unknown,
key: React.Key | undefined,
isStatic: boolean,
source?: JSXSource,
self?: unknown,
): React.ReactElement;
-24
View File
@@ -1,24 +0,0 @@
import * as React from "./";
export { Fragment, JSX } from "./";
/**
* Create a React element.
*
* You should not use this function directly. Use JSX and a transpiler instead.
*/
export function jsx(
type: React.ElementType,
props: unknown,
key?: React.Key,
): React.ReactElement;
/**
* Create a React element.
*
* You should not use this function directly. Use JSX and a transpiler instead.
*/
export function jsxs(
type: React.ElementType,
props: unknown,
key?: React.Key,
): React.ReactElement;
-21
View File
@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2019-present, Yuxi (Evan) You and Vite contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-169
View File
@@ -1,169 +0,0 @@
# @vitejs/plugin-react [![npm](https://img.shields.io/npm/v/@vitejs/plugin-react.svg)](https://npmjs.com/package/@vitejs/plugin-react)
The default Vite plugin for React projects.
- enable [Fast Refresh](https://www.npmjs.com/package/react-refresh) in development (requires react >= 16.9)
- use the [automatic JSX runtime](https://legacy.reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html)
- small installation size
```js
// vite.config.js
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
})
```
## Options
### include
Includes `.js`, `.jsx`, `.ts` & `.tsx` by default. This option can be used to add fast refresh to `.mdx` files:
```js
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import mdx from '@mdx-js/rollup'
export default defineConfig({
plugins: [
{ enforce: 'pre', ...mdx() },
react({ include: /\.(mdx|js|jsx|ts|tsx)$/ }),
],
})
```
### exclude
The default value is `/node_modules/`. You may use it to exclude JSX/TSX files that runs in a worker or are not React files.
Except if explicitly desired, you should keep `node_modules` in the exclude list:
```js
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [
react({ exclude: [/\/pdf\//, /\.solid\.tsx$/, /\/node_modules\//] }),
],
})
```
### jsxImportSource
Control where the JSX factory is imported from. By default, this is inferred from `jsxImportSource` from corresponding a tsconfig file for a transformed file.
```js
react({ jsxImportSource: '@emotion/react' })
```
### jsxRuntime
By default, the plugin uses the [automatic JSX runtime](https://legacy.reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html). However, if you encounter any issues, you may opt out using the `jsxRuntime` option.
```js
react({ jsxRuntime: 'classic' })
```
### reactRefreshHost
The `reactRefreshHost` option is only necessary in a module federation context. It enables HMR to work between a remote & host application. In your remote Vite config, you would add your host origin:
```js
react({ reactRefreshHost: 'http://localhost:3000' })
```
Under the hood, this simply updates the React Fash Refresh runtime URL from `/@react-refresh` to `http://localhost:3000/@react-refresh` to ensure there is only one Refresh runtime across the whole application. Note that if you define `base` option in the host application, you need to include it in the option, like: `http://localhost:3000/{base}`.
## React Compiler
[React Compiler](https://react.dev/learn/react-compiler) support is available via the exported `reactCompilerPreset` helper, which requires [`@rolldown/plugin-babel`](https://npmx.dev/package/@rolldown/plugin-babel) and [`babel-plugin-react-compiler`](https://npmx.dev/package/babel-plugin-react-compiler) and [`@babel/core`](https://npmx.dev/package/@babel/core) as peer dependencies:
```sh
npm install -D @rolldown/plugin-babel @babel/core babel-plugin-react-compiler
```
If you are using TypeScript, you will also need to install [`@types/babel__core`](https://npmx.dev/package/@types/babel__core):
```sh
npm install -D @types/babel__core
```
```js
// vite.config.js
import { defineConfig } from 'vite'
import react, { reactCompilerPreset } from '@vitejs/plugin-react'
import babel from '@rolldown/plugin-babel'
export default defineConfig({
plugins: [react(), babel({ presets: [reactCompilerPreset()] })],
})
```
The `reactCompilerPreset` accepts an optional options object with the following properties:
- `compilationMode` — Set to `'annotation'` to only compile components annotated with `"use memo"`.
- `target` — Set to `'17'` or `'18'` to target older React versions (uses `react-compiler-runtime` instead of `react/compiler-runtime`).
Additional options can be found in the [documentation](https://react.dev/reference/react-compiler/configuration).
```js
babel({
presets: [reactCompilerPreset({ compilationMode: 'annotation' })],
})
```
> [!TIP]
>
> `reactCompilerPreset` is only a convenient helper with a preconfigured filter. You can configure override the filters to fit your project structure or code. For example, if you know a large portion of your files are never React/hook-related or won't benefit from the React Compiler, you can aggressively exclude them via `rolldown.filter`:
>
> ```js
> const myPreset = reactCompilerPreset()
> myPreset.rolldown.filter.id.exclude = ['src/legacy/**', 'src/utils/**']
>
> babel({
> presets: [myPreset],
> })
> ```
## `@vitejs/plugin-react/preamble`
The package provides `@vitejs/plugin-react/preamble` to initialize HMR runtime from client entrypoint for SSR applications which don't use [`transformIndexHtml` API](https://vite.dev/guide/api-javascript.html#vitedevserver). For example:
```js
// [entry.client.js]
import '@vitejs/plugin-react/preamble'
```
Alternatively, you can manually call `transformIndexHtml` during SSR, which sets up equivalent initialization code. Here's an example for an Express server:
```js
app.get('/', async (req, res, next) => {
try {
let html = fs.readFileSync(path.resolve(root, 'index.html'), 'utf-8')
// Transform HTML using Vite plugins.
html = await viteServer.transformIndexHtml(req.url, html)
res.send(html)
} catch (e) {
return next(e)
}
})
```
Otherwise, you'll get the following error:
```
Uncaught Error: @vitejs/plugin-react can't detect preamble. Something is wrong.
```
## Consistent components exports
For React refresh to work correctly, your file should only export React components. You can find a good explanation in the [Gatsby docs](https://www.gatsbyjs.com/docs/reference/local-development/fast-refresh/#how-it-works).
If an incompatible change in exports is found, the module will be invalidated and HMR will propagate. To make it easier to export simple constants alongside your component, the module is only invalidated when their value changes.
You can catch mistakes and get more detailed warnings with this [ESLint rule](https://github.com/ArnaudBarre/eslint-plugin-react-refresh), this [Oxlint rule](https://oxc.rs/docs/guide/usage/linter/rules/react/only-export-components.html), or this [Biome rule](https://biomejs.dev/linter/rules/use-component-export-only-modules).
-48
View File
@@ -1,48 +0,0 @@
import { Plugin } from "vite";
import { ReactCompilerBabelPluginOptions, RolldownBabelPreset } from "#optionalTypes";
//#region src/reactCompilerPreset.d.ts
declare const reactCompilerPreset: (options?: ReactCompilerBabelPluginOptions) => RolldownBabelPreset;
//#endregion
//#region src/index.d.ts
interface Options {
/**
* Can be used to process extra files like `.mdx`
* @example include: /\.(mdx|js|jsx|ts|tsx)$/
* @default /\.[tj]sx?$/
*/
include?: string | RegExp | Array<string | RegExp>;
/**
* Can be used to exclude JSX/TSX files that runs in a worker or are not React files.
* Except if explicitly desired, you should keep node_modules in the exclude list
* @example exclude: [/\/pdf\//, /\.solid\.tsx$/, /\/node_modules\//]
* @default /\/node_modules\//
*/
exclude?: string | RegExp | Array<string | RegExp>;
/**
* Control where the JSX factory is imported from.
* https://oxc.rs/docs/guide/usage/transformer/jsx.html#import-source
* @default 'react'
*/
jsxImportSource?: string;
/**
* Note: Skipping React import with classic runtime is not supported from v4
* @default "automatic"
*/
jsxRuntime?: 'classic' | 'automatic';
/**
* React Fast Refresh runtime URL prefix.
* Useful in a module federation context to enable HMR by specifying
* the host application URL in the Vite config of a remote application.
* @example
* reactRefreshHost: 'http://localhost:3000'
*/
reactRefreshHost?: string;
}
declare function viteReact(opts?: Options): Plugin[];
declare namespace viteReact {
var preambleCode: string;
}
declare function viteReactForCjs(this: unknown, options: Options): Plugin[];
//#endregion
export { Options, viteReact as default, viteReactForCjs as "module.exports", reactCompilerPreset };
-200
View File
@@ -1,200 +0,0 @@
import { readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { exactRegex, makeIdFiltersToMatchWithQuery } from "@rolldown/pluginutils";
import { reactRefreshWrapperPlugin } from "vite/internal";
//#region ../common/refresh-utils.ts
const runtimePublicPath = "/@react-refresh";
const preambleCode = `import { injectIntoGlobalHook } from "__BASE__${runtimePublicPath.slice(1)}";
injectIntoGlobalHook(window);
window.$RefreshReg$ = () => {};
window.$RefreshSig$ = () => (type) => type;`;
const getPreambleCode = (base) => preambleCode.replace("__BASE__", base);
function virtualPreamblePlugin({ name, isEnabled }) {
return {
name: "vite:react-virtual-preamble",
resolveId: {
order: "pre",
filter: { id: exactRegex(name) },
handler(source) {
if (source === name) return "\0" + source;
}
},
load: {
filter: { id: exactRegex("\0" + name) },
handler(id) {
if (id === "\0" + name) {
if (isEnabled()) return preambleCode.replace("__BASE__", "/");
return "";
}
}
}
};
}
//#endregion
//#region ../common/warning.ts
const silenceUseClientWarning = (userConfig) => ({ rollupOptions: { onwarn(warning, defaultHandler) {
if (warning.code === "MODULE_LEVEL_DIRECTIVE" && (warning.message.includes("use client") || warning.message.includes("use server"))) return;
if (warning.code === "SOURCEMAP_ERROR" && warning.message.includes("resolve original location") && warning.pos === 0) return;
if (userConfig.build?.rollupOptions?.onwarn) userConfig.build.rollupOptions.onwarn(warning, defaultHandler);
else defaultHandler(warning);
} } });
//#endregion
//#region src/reactCompilerPreset.ts
const defaultCodeFilter = /forwardRef|memo|(?:const|let|var|function)\s+(?:[A-Z]|use[A-Z0-9])|(?:[A-Z]|use[A-Z0-9])[^\s:=(){}[\],;]*\s*(?:\(|[:=]\s*(?:function|\())/;
const reactCompilerPreset = (options = {}) => ({
preset: () => ({ plugins: [["babel-plugin-react-compiler", options]] }),
rolldown: {
filter: { code: options.compilationMode === "annotation" ? /['"]use memo['"]/ : defaultCodeFilter },
applyToEnvironmentHook: (env) => env.config.consumer === "client",
optimizeDeps: { include: options.target === "17" || options.target === "18" ? ["react-compiler-runtime"] : ["react/compiler-runtime"] }
}
});
//#endregion
//#region src/index.ts
const refreshRuntimePath = join(dirname(fileURLToPath(import.meta.url)), "refresh-runtime.js");
const defaultIncludeRE = /\.[tj]sx?$/;
const defaultExcludeRE = /\/node_modules\//;
function viteReact(opts = {}) {
const include = opts.include ?? defaultIncludeRE;
const exclude = opts.exclude ?? defaultExcludeRE;
const jsxImportSource = opts.jsxImportSource ?? "react";
const jsxImportRuntime = `${jsxImportSource}/jsx-runtime`;
const jsxImportDevRuntime = `${jsxImportSource}/jsx-dev-runtime`;
let runningInVite = false;
let isProduction = true;
let skipFastRefresh = true;
let base;
let isBundledDev = false;
const viteBabel = {
name: "vite:react-babel",
enforce: "pre",
config(_userConfig, { command }) {
if (opts.jsxRuntime === "classic") return { oxc: {
jsx: {
runtime: "classic",
refresh: command === "serve"
},
jsxRefreshInclude: makeIdFiltersToMatchWithQuery(include),
jsxRefreshExclude: makeIdFiltersToMatchWithQuery(exclude)
} };
else return {
oxc: {
jsx: {
runtime: "automatic",
importSource: opts.jsxImportSource,
refresh: command === "serve"
},
jsxRefreshInclude: makeIdFiltersToMatchWithQuery(include),
jsxRefreshExclude: makeIdFiltersToMatchWithQuery(exclude)
},
optimizeDeps: { rolldownOptions: { transform: { jsx: { runtime: "automatic" } } } }
};
},
configResolved(config) {
runningInVite = true;
base = config.base;
if (config.experimental.bundledDev) isBundledDev = true;
isProduction = config.isProduction;
skipFastRefresh = isProduction || config.command === "build" || config.server.hmr === false;
},
options(options) {
if (!runningInVite) {
options.transform ??= {};
options.transform.jsx = {
runtime: opts.jsxRuntime,
importSource: opts.jsxImportSource
};
return options;
}
}
};
const viteRefreshWrapper = {
name: "vite:react:refresh-wrapper",
apply: "serve",
async applyToEnvironment(env) {
if (env.config.consumer !== "client" || skipFastRefresh) return false;
return reactRefreshWrapperPlugin({
cwd: process.cwd(),
include: makeIdFiltersToMatchWithQuery(include),
exclude: makeIdFiltersToMatchWithQuery(exclude),
jsxImportSource,
reactRefreshHost: opts.reactRefreshHost ?? ""
});
}
};
const viteConfigPost = {
name: "vite:react:config-post",
enforce: "post",
config(userConfig) {
if (userConfig.server?.hmr === false) return { oxc: { jsx: { refresh: false } } };
}
};
const viteReactRefreshBundledDevMode = {
name: "vite:react-refresh-fbm",
enforce: "pre",
transformIndexHtml: {
handler() {
if (!skipFastRefresh && isBundledDev) return [{
tag: "script",
attrs: { type: "module" },
children: getPreambleCode("/")
}];
},
order: "pre"
}
};
const dependencies = [
"react",
"react-dom",
jsxImportDevRuntime,
jsxImportRuntime
];
return [
viteBabel,
viteRefreshWrapper,
viteConfigPost,
viteReactRefreshBundledDevMode,
{
name: "vite:react-refresh",
enforce: "pre",
config: (userConfig) => ({
build: silenceUseClientWarning(userConfig),
optimizeDeps: { include: dependencies }
}),
resolveId: {
filter: { id: exactRegex(runtimePublicPath) },
handler(id) {
if (id === "/@react-refresh") return id;
}
},
load: {
filter: { id: exactRegex(runtimePublicPath) },
handler(id) {
if (id === "/@react-refresh") return readFileSync(refreshRuntimePath, "utf-8").replace(/__README_URL__/g, "https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react");
}
},
transformIndexHtml() {
if (!skipFastRefresh && !isBundledDev) return [{
tag: "script",
attrs: { type: "module" },
children: getPreambleCode(base)
}];
}
},
virtualPreamblePlugin({
name: "@vitejs/plugin-react/preamble",
isEnabled: () => !skipFastRefresh && !isBundledDev
})
];
}
viteReact.preambleCode = preambleCode;
function viteReactForCjs(options) {
return viteReact.call(this, options);
}
Object.assign(viteReactForCjs, {
default: viteReactForCjs,
reactCompilerPreset
});
//#endregion
export { viteReact as default, viteReactForCjs as "module.exports", reactCompilerPreset };
-663
View File
@@ -1,663 +0,0 @@
/* global window */
/* eslint-disable eqeqeq, prefer-const, @typescript-eslint/no-empty-function */
/*! Copyright (c) Meta Platforms, Inc. and affiliates. **/
/**
* This is simplified pure-js version of https://github.com/facebook/react/blob/main/packages/react-refresh/src/ReactFreshRuntime.js
* without IE11 compatibility and verbose isDev checks.
* Some utils are appended at the bottom for HMR integration.
*/
const REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref')
const REACT_MEMO_TYPE = Symbol.for('react.memo')
// We never remove these associations.
// It's OK to reference families, but use WeakMap/Set for types.
let allFamiliesByID = new Map()
let allFamiliesByType = new WeakMap()
let allSignaturesByType = new WeakMap()
// This WeakMap is read by React, so we only put families
// that have actually been edited here. This keeps checks fast.
const updatedFamiliesByType = new WeakMap()
// This is cleared on every performReactRefresh() call.
// It is an array of [Family, NextType] tuples.
let pendingUpdates = []
// This is injected by the renderer via DevTools global hook.
const helpersByRendererID = new Map()
const helpersByRoot = new Map()
// We keep track of mounted roots so we can schedule updates.
const mountedRoots = new Set()
// If a root captures an error, we remember it so we can retry on edit.
const failedRoots = new Set()
// We also remember the last element for every root.
// It needs to be weak because we do this even for roots that failed to mount.
// If there is no WeakMap, we won't attempt to do retrying.
let rootElements = new WeakMap()
let isPerformingRefresh = false
function computeFullKey(signature) {
if (signature.fullKey !== null) {
return signature.fullKey
}
let fullKey = signature.ownKey
let hooks
try {
hooks = signature.getCustomHooks()
} catch (err) {
// This can happen in an edge case, e.g. if expression like Foo.useSomething
// depends on Foo which is lazily initialized during rendering.
// In that case just assume we'll have to remount.
signature.forceReset = true
signature.fullKey = fullKey
return fullKey
}
for (let i = 0; i < hooks.length; i++) {
const hook = hooks[i]
if (typeof hook !== 'function') {
// Something's wrong. Assume we need to remount.
signature.forceReset = true
signature.fullKey = fullKey
return fullKey
}
const nestedHookSignature = allSignaturesByType.get(hook)
if (nestedHookSignature === undefined) {
// No signature means Hook wasn't in the source code, e.g. in a library.
// We'll skip it because we can assume it won't change during this session.
continue
}
const nestedHookKey = computeFullKey(nestedHookSignature)
if (nestedHookSignature.forceReset) {
signature.forceReset = true
}
fullKey += '\n---\n' + nestedHookKey
}
signature.fullKey = fullKey
return fullKey
}
function haveEqualSignatures(prevType, nextType) {
const prevSignature = allSignaturesByType.get(prevType)
const nextSignature = allSignaturesByType.get(nextType)
if (prevSignature === undefined && nextSignature === undefined) {
return true
}
if (prevSignature === undefined || nextSignature === undefined) {
return false
}
if (computeFullKey(prevSignature) !== computeFullKey(nextSignature)) {
return false
}
if (nextSignature.forceReset) {
return false
}
return true
}
function isReactClass(type) {
return type.prototype && type.prototype.isReactComponent
}
function canPreserveStateBetween(prevType, nextType) {
if (isReactClass(prevType) || isReactClass(nextType)) {
return false
}
if (haveEqualSignatures(prevType, nextType)) {
return true
}
return false
}
function resolveFamily(type) {
// Only check updated types to keep lookups fast.
return updatedFamiliesByType.get(type)
}
// This is a safety mechanism to protect against rogue getters and Proxies.
function getProperty(object, property) {
try {
return object[property]
} catch (err) {
// Intentionally ignore.
return undefined
}
}
function performReactRefresh() {
if (pendingUpdates.length === 0) {
return null
}
if (isPerformingRefresh) {
return null
}
isPerformingRefresh = true
try {
const staleFamilies = new Set()
const updatedFamilies = new Set()
const updates = pendingUpdates
pendingUpdates = []
updates.forEach(([family, nextType]) => {
// Now that we got a real edit, we can create associations
// that will be read by the React reconciler.
const prevType = family.current
updatedFamiliesByType.set(prevType, family)
updatedFamiliesByType.set(nextType, family)
family.current = nextType
// Determine whether this should be a re-render or a re-mount.
if (canPreserveStateBetween(prevType, nextType)) {
updatedFamilies.add(family)
} else {
staleFamilies.add(family)
}
})
// TODO: rename these fields to something more meaningful.
const update = {
updatedFamilies, // Families that will re-render preserving state
staleFamilies, // Families that will be remounted
}
helpersByRendererID.forEach((helpers) => {
// Even if there are no roots, set the handler on first update.
// This ensures that if *new* roots are mounted, they'll use the resolve handler.
helpers.setRefreshHandler(resolveFamily)
})
let didError = false
let firstError = null
// We snapshot maps and sets that are mutated during commits.
// If we don't do this, there is a risk they will be mutated while
// we iterate over them. For example, trying to recover a failed root
// may cause another root to be added to the failed list -- an infinite loop.
const failedRootsSnapshot = new Set(failedRoots)
const mountedRootsSnapshot = new Set(mountedRoots)
const helpersByRootSnapshot = new Map(helpersByRoot)
failedRootsSnapshot.forEach((root) => {
const helpers = helpersByRootSnapshot.get(root)
if (helpers === undefined) {
throw new Error(
'Could not find helpers for a root. This is a bug in React Refresh.',
)
}
if (!failedRoots.has(root)) {
// No longer failed.
}
if (rootElements === null) {
return
}
if (!rootElements.has(root)) {
return
}
const element = rootElements.get(root)
try {
helpers.scheduleRoot(root, element)
} catch (err) {
if (!didError) {
didError = true
firstError = err
}
// Keep trying other roots.
}
})
mountedRootsSnapshot.forEach((root) => {
const helpers = helpersByRootSnapshot.get(root)
if (helpers === undefined) {
throw new Error(
'Could not find helpers for a root. This is a bug in React Refresh.',
)
}
if (!mountedRoots.has(root)) {
// No longer mounted.
}
try {
helpers.scheduleRefresh(root, update)
} catch (err) {
if (!didError) {
didError = true
firstError = err
}
// Keep trying other roots.
}
})
if (didError) {
throw firstError
}
return update
} finally {
isPerformingRefresh = false
}
}
export function register(type, id) {
if (type === null) {
return
}
if (typeof type !== 'function' && typeof type !== 'object') {
return
}
// This can happen in an edge case, e.g. if we register
// return value of a HOC but it returns a cached component.
// Ignore anything but the first registration for each type.
if (allFamiliesByType.has(type)) {
return
}
// Create family or remember to update it.
// None of this bookkeeping affects reconciliation
// until the first performReactRefresh() call above.
let family = allFamiliesByID.get(id)
if (family === undefined) {
family = { current: type }
allFamiliesByID.set(id, family)
} else {
pendingUpdates.push([family, type])
}
allFamiliesByType.set(type, family)
// Visit inner types because we might not have registered them.
if (typeof type === 'object' && type !== null) {
switch (getProperty(type, '$$typeof')) {
case REACT_FORWARD_REF_TYPE:
register(type.render, id + '$render')
break
case REACT_MEMO_TYPE:
register(type.type, id + '$type')
break
}
}
}
function setSignature(type, key, forceReset, getCustomHooks) {
if (!allSignaturesByType.has(type)) {
allSignaturesByType.set(type, {
forceReset,
ownKey: key,
fullKey: null,
getCustomHooks: getCustomHooks || (() => []),
})
}
// Visit inner types because we might not have signed them.
if (typeof type === 'object' && type !== null) {
switch (getProperty(type, '$$typeof')) {
case REACT_FORWARD_REF_TYPE:
setSignature(type.render, key, forceReset, getCustomHooks)
break
case REACT_MEMO_TYPE:
setSignature(type.type, key, forceReset, getCustomHooks)
break
}
}
}
// This is lazily called during first render for a type.
// It captures Hook list at that time so inline requires don't break comparisons.
function collectCustomHooksForSignature(type) {
const signature = allSignaturesByType.get(type)
if (signature !== undefined) {
computeFullKey(signature)
}
}
export function injectIntoGlobalHook(globalObject) {
// For React Native, the global hook will be set up by require('react-devtools-core').
// That code will run before us. So we need to monkeypatch functions on existing hook.
// For React Web, the global hook will be set up by the extension.
// This will also run before us.
let hook = globalObject.__REACT_DEVTOOLS_GLOBAL_HOOK__
if (hook === undefined) {
// However, if there is no DevTools extension, we'll need to set up the global hook ourselves.
// Note that in this case it's important that renderer code runs *after* this method call.
// Otherwise, the renderer will think that there is no global hook, and won't do the injection.
let nextID = 0
globalObject.__REACT_DEVTOOLS_GLOBAL_HOOK__ = hook = {
renderers: new Map(),
supportsFiber: true,
inject: (injected) => nextID++,
onScheduleFiberRoot: (id, root, children) => {},
onCommitFiberRoot: (id, root, maybePriorityLevel, didError) => {},
onCommitFiberUnmount() {},
}
}
if (hook.isDisabled) {
// This isn't a real property on the hook, but it can be set to opt out
// of DevTools integration and associated warnings and logs.
// Using console['warn'] to evade Babel and ESLint
console['warn'](
'Something has shimmed the React DevTools global hook (__REACT_DEVTOOLS_GLOBAL_HOOK__). ' +
'Fast Refresh is not compatible with this shim and will be disabled.',
)
return
}
// Here, we just want to get a reference to scheduleRefresh.
const oldInject = hook.inject
hook.inject = function (injected) {
const id = oldInject.apply(this, arguments)
if (
typeof injected.scheduleRefresh === 'function' &&
typeof injected.setRefreshHandler === 'function'
) {
// This version supports React Refresh.
helpersByRendererID.set(id, injected)
}
return id
}
// Do the same for any already injected roots.
// This is useful if ReactDOM has already been initialized.
// https://github.com/facebook/react/issues/17626
hook.renderers.forEach((injected, id) => {
if (
typeof injected.scheduleRefresh === 'function' &&
typeof injected.setRefreshHandler === 'function'
) {
// This version supports React Refresh.
helpersByRendererID.set(id, injected)
}
})
// We also want to track currently mounted roots.
const oldOnCommitFiberRoot = hook.onCommitFiberRoot
const oldOnScheduleFiberRoot = hook.onScheduleFiberRoot || (() => {})
hook.onScheduleFiberRoot = function (id, root, children) {
if (!isPerformingRefresh) {
// If it was intentionally scheduled, don't attempt to restore.
// This includes intentionally scheduled unmounts.
failedRoots.delete(root)
if (rootElements !== null) {
rootElements.set(root, children)
}
}
return oldOnScheduleFiberRoot.apply(this, arguments)
}
hook.onCommitFiberRoot = function (id, root, maybePriorityLevel, didError) {
const helpers = helpersByRendererID.get(id)
if (helpers !== undefined) {
helpersByRoot.set(root, helpers)
const current = root.current
const alternate = current.alternate
// We need to determine whether this root has just (un)mounted.
// This logic is copy-pasted from similar logic in the DevTools backend.
// If this breaks with some refactoring, you'll want to update DevTools too.
if (alternate !== null) {
const wasMounted =
alternate.memoizedState != null &&
alternate.memoizedState.element != null &&
mountedRoots.has(root)
const isMounted =
current.memoizedState != null && current.memoizedState.element != null
if (!wasMounted && isMounted) {
// Mount a new root.
mountedRoots.add(root)
failedRoots.delete(root)
} else if (wasMounted && isMounted) {
// Update an existing root.
// This doesn't affect our mounted root Set.
} else if (wasMounted && !isMounted) {
// Unmount an existing root.
mountedRoots.delete(root)
if (didError) {
// We'll remount it on future edits.
failedRoots.add(root)
} else {
helpersByRoot.delete(root)
}
} else if (!wasMounted && !isMounted) {
if (didError) {
// We'll remount it on future edits.
failedRoots.add(root)
}
}
} else {
// Mount a new root.
mountedRoots.add(root)
}
}
// Always call the decorated DevTools hook.
return oldOnCommitFiberRoot.apply(this, arguments)
}
}
// This is a wrapper over more primitive functions for setting signature.
// Signatures let us decide whether the Hook order has changed on refresh.
//
// This function is intended to be used as a transform target, e.g.:
// var _s = createSignatureFunctionForTransform()
//
// function Hello() {
// const [foo, setFoo] = useState(0);
// const value = useCustomHook();
// _s(); /* Call without arguments triggers collecting the custom Hook list.
// * This doesn't happen during the module evaluation because we
// * don't want to change the module order with inline requires.
// * Next calls are noops. */
// return <h1>Hi</h1>;
// }
//
// /* Call with arguments attaches the signature to the type: */
// _s(
// Hello,
// 'useState{[foo, setFoo]}(0)',
// () => [useCustomHook], /* Lazy to avoid triggering inline requires */
// );
export function createSignatureFunctionForTransform() {
let savedType
let hasCustomHooks
let didCollectHooks = false
return function (type, key, forceReset, getCustomHooks) {
if (typeof key === 'string') {
// We're in the initial phase that associates signatures
// with the functions. Note this may be called multiple times
// in HOC chains like _s(hoc1(_s(hoc2(_s(actualFunction))))).
if (!savedType) {
// We're in the innermost call, so this is the actual type.
// $FlowFixMe[escaped-generic] discovered when updating Flow
savedType = type
hasCustomHooks = typeof getCustomHooks === 'function'
}
// Set the signature for all types (even wrappers!) in case
// they have no signatures of their own. This is to prevent
// problems like https://github.com/facebook/react/issues/20417.
if (
type != null &&
(typeof type === 'function' || typeof type === 'object')
) {
setSignature(type, key, forceReset, getCustomHooks)
}
return type
} else {
// We're in the _s() call without arguments, which means
// this is the time to collect custom Hook signatures.
// Only do this once. This path is hot and runs *inside* every render!
if (!didCollectHooks && hasCustomHooks) {
didCollectHooks = true
collectCustomHooksForSignature(savedType)
}
}
}
}
function isLikelyComponentType(type) {
switch (typeof type) {
case 'function': {
// First, deal with classes.
if (type.prototype != null) {
if (type.prototype.isReactComponent) {
// React class.
return true
}
const ownNames = Object.getOwnPropertyNames(type.prototype)
if (ownNames.length > 1 || ownNames[0] !== 'constructor') {
// This looks like a class.
return false
}
if (type.prototype.__proto__ !== Object.prototype) {
// It has a superclass.
return false
}
// Pass through.
// This looks like a regular function with empty prototype.
}
// For plain functions and arrows, use name as a heuristic.
const name = type.name || type.displayName
return typeof name === 'string' && /^[A-Z]/.test(name)
}
case 'object': {
if (type != null) {
switch (getProperty(type, '$$typeof')) {
case REACT_FORWARD_REF_TYPE:
case REACT_MEMO_TYPE:
// Definitely React components.
return true
default:
return false
}
}
return false
}
default: {
return false
}
}
}
function isCompoundComponent(type) {
if (!isPlainObject(type)) return false
for (const key in type) {
if (!isLikelyComponentType(type[key])) return false
}
return true
}
function isPlainObject(obj) {
return (
Object.prototype.toString.call(obj) === '[object Object]' &&
(obj.constructor === Object || obj.constructor === undefined)
)
}
/**
* Plugin utils
*/
// Taken from https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/main/lib/runtime/RefreshUtils.js#L141
// This allows to resister components not detected by SWC like styled component
export function registerExportsForReactRefresh(filename, moduleExports) {
for (const key in moduleExports) {
if (key === '__esModule') continue
const exportValue = moduleExports[key]
if (isLikelyComponentType(exportValue)) {
// 'export' is required to avoid key collision when renamed exports that
// shadow a local component name: https://github.com/vitejs/vite-plugin-react/issues/116
// The register function has an identity check to not register twice the same component,
// so this is safe to not used the same key here.
register(exportValue, filename + ' export ' + key)
} else if (isCompoundComponent(exportValue)) {
for (const subKey in exportValue) {
register(
exportValue[subKey],
filename + ' export ' + key + '-' + subKey,
)
}
}
}
}
function debounce(fn, delay) {
let handle
return () => {
clearTimeout(handle)
handle = setTimeout(fn, delay)
}
}
const hooks = []
window.__registerBeforePerformReactRefresh = (cb) => {
hooks.push(cb)
}
const enqueueUpdate = debounce(async () => {
if (hooks.length) await Promise.all(hooks.map((cb) => cb()))
performReactRefresh()
}, 16)
export function validateRefreshBoundaryAndEnqueueUpdate(
id,
prevExports,
nextExports,
) {
const ignoredExports = window.__getReactRefreshIgnoredExports?.({ id }) ?? []
if (
predicateOnExport(
ignoredExports,
prevExports,
(key) => key in nextExports,
) !== true
) {
return 'Could not Fast Refresh (export removed)'
}
if (
predicateOnExport(
ignoredExports,
nextExports,
(key) => key in prevExports,
) !== true
) {
return 'Could not Fast Refresh (new export)'
}
let hasExports = false
const allExportsAreComponentsOrUnchanged = predicateOnExport(
ignoredExports,
nextExports,
(key, value) => {
hasExports = true
if (isLikelyComponentType(value)) return true
if (isCompoundComponent(value)) return true
return prevExports[key] === nextExports[key]
},
)
if (hasExports && allExportsAreComponentsOrUnchanged === true) {
enqueueUpdate()
} else {
return `Could not Fast Refresh ("${allExportsAreComponentsOrUnchanged}" export is incompatible). Learn more at __README_URL__#consistent-components-exports`
}
}
function predicateOnExport(ignoredExports, moduleExports, predicate) {
for (const key in moduleExports) {
if (ignoredExports.includes(key)) continue
if (!predicate(key, moduleExports[key])) return key
}
return true
}
// Hides vite-ignored dynamic import so that Vite can skip analysis if no other
// dynamic import is present (https://github.com/vitejs/vite/pull/12732)
export const __hmr_import = (module) => import(/* @vite-ignore */ module)
// For backwards compatibility with @vitejs/plugin-react.
export default { injectIntoGlobalHook }
-87
View File
@@ -1,87 +0,0 @@
{
"name": "@vitejs/plugin-react",
"version": "6.0.3",
"description": "The default Vite plugin for React projects",
"keywords": [
"fast refresh",
"react",
"react-refresh",
"vite",
"vite-plugin"
],
"homepage": "https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react#readme",
"bugs": {
"url": "https://github.com/vitejs/vite-plugin-react/issues"
},
"license": "MIT",
"author": "Evan You",
"contributors": [
"Alec Larson",
"Arnaud Barré"
],
"repository": {
"type": "git",
"url": "git+https://github.com/vitejs/vite-plugin-react.git",
"directory": "packages/plugin-react"
},
"files": [
"dist",
"types"
],
"type": "module",
"imports": {
"#optionalTypes": "./types/optionalTypes.d.ts"
},
"exports": {
".": "./dist/index.js",
"./preamble": "./types/preamble.d.ts"
},
"scripts": {
"dev": "tsdown --watch ./src --watch ../common",
"build": "tsdown",
"prepublishOnly": "npm run build",
"test-unit": "vitest run"
},
"dependencies": {
"@rolldown/pluginutils": "^1.0.1"
},
"devDependencies": {
"@babel/core": "8.0.0-rc.6",
"@rolldown/plugin-babel": "^0.2.3",
"@vitejs/react-common": "workspace:*",
"babel-plugin-react-compiler": "^1.0.0",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"rolldown": "^1.1.1",
"tsdown": "^0.22.2",
"vite": "^8.0.16"
},
"peerDependencies": {
"@rolldown/plugin-babel": "^0.1.7 || ^0.2.0",
"babel-plugin-react-compiler": "^1.0.0",
"vite": "^8.0.0"
},
"peerDependenciesMeta": {
"@rolldown/plugin-babel": {
"optional": true
},
"babel-plugin-react-compiler": {
"optional": true
}
},
"engines": {
"node": "^20.19.0 || >=22.12.0"
},
"compatiblePackages": {
"schemaVersion": 1,
"rolldown": {
"type": "compatible",
"versions": "^1.0.0",
"note": "You can use Rolldown's built-in feature directly."
},
"rollup": {
"type": "incompatible",
"reason": "Uses Rolldown-specific APIs or Vite-specific APIs"
}
}
}
-12
View File
@@ -1,12 +0,0 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
// @ts-ignore --- `@rolldown/plugin-babel` is an optional peer dependency, so this may cause an error
import type * as pluginBabel from '@rolldown/plugin-babel'
// @ts-ignore --- `babel-plugin-react-compiler` is an optional peer dependency, so this may cause an error
import type * as babelPluginReactCompiler from 'babel-plugin-react-compiler'
// @ts-ignore --- `@rolldown/plugin-babel` is an optional peer dependency, so this may cause an error
export type RolldownBabelPreset = pluginBabel.RolldownBabelPreset
// @ts-ignore --- `babel-plugin-react-compiler` is an optional peer dependency, so this may cause an error
export type ReactCompilerBabelPluginOptions =
babelPluginReactCompiler.PluginOptions
-1
View File
@@ -1 +0,0 @@
export {}
-19
View File
@@ -1,19 +0,0 @@
Copyright (c) 2017-2018 Fredrik Nicol
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-291
View File
@@ -1,291 +0,0 @@
# CSSType
[![npm](https://img.shields.io/npm/v/csstype.svg)](https://www.npmjs.com/package/csstype)
TypeScript and Flow definitions for CSS, generated by [data from MDN](https://github.com/mdn/data). It provides autocompletion and type checking for CSS properties and values.
**TypeScript**
```ts
import type * as CSS from 'csstype';
const style: CSS.Properties = {
colour: 'white', // Type error on property
textAlign: 'middle', // Type error on value
};
```
**Flow**
```js
// @flow strict
import * as CSS from 'csstype';
const style: CSS.Properties<> = {
colour: 'white', // Type error on property
textAlign: 'middle', // Type error on value
};
```
_Further examples below will be in TypeScript!_
## Getting started
```sh
$ npm install csstype
```
## Table of content
- [Style types](#style-types)
- [At-rule types](#at-rule-types)
- [Pseudo types](#pseudo-types)
- [Generics](#generics)
- [Usage](#usage)
- [What should I do when I get type errors?](#what-should-i-do-when-i-get-type-errors)
- [Version 3.0](#version-30)
- [Contributing](#contributing)
## Style types
Properties are categorized in different uses and in several technical variations to provide typings that suits as many as possible.
| | Default | `Hyphen` | `Fallback` | `HyphenFallback` |
| -------------- | -------------------- | -------------------------- | ---------------------------- | ---------------------------------- |
| **All** | `Properties` | `PropertiesHyphen` | `PropertiesFallback` | `PropertiesHyphenFallback` |
| **`Standard`** | `StandardProperties` | `StandardPropertiesHyphen` | `StandardPropertiesFallback` | `StandardPropertiesHyphenFallback` |
| **`Vendor`** | `VendorProperties` | `VendorPropertiesHyphen` | `VendorPropertiesFallback` | `VendorPropertiesHyphenFallback` |
| **`Obsolete`** | `ObsoleteProperties` | `ObsoletePropertiesHyphen` | `ObsoletePropertiesFallback` | `ObsoletePropertiesHyphenFallback` |
| **`Svg`** | `SvgProperties` | `SvgPropertiesHyphen` | `SvgPropertiesFallback` | `SvgPropertiesHyphenFallback` |
Categories:
- **All** - Includes `Standard`, `Vendor`, `Obsolete` and `Svg`
- **`Standard`** - Current properties and extends subcategories `StandardLonghand` and `StandardShorthand` _(e.g. `StandardShorthandProperties`)_
- **`Vendor`** - Vendor prefixed properties and extends subcategories `VendorLonghand` and `VendorShorthand` _(e.g. `VendorShorthandProperties`)_
- **`Obsolete`** - Removed or deprecated properties
- **`Svg`** - SVG-specific properties
Variations:
- **Default** - JavaScript (camel) cased property names
- **`Hyphen`** - CSS (kebab) cased property names
- **`Fallback`** - Also accepts array of values e.g. `string | string[]`
## At-rule types
At-rule interfaces with descriptors.
**TypeScript**: These will be found in the `AtRule` namespace, e.g. `AtRule.Viewport`.
**Flow**: These will be prefixed with `AtRule$`, e.g. `AtRule$Viewport`.
| | Default | `Hyphen` | `Fallback` | `HyphenFallback` |
| -------------------- | -------------- | -------------------- | ---------------------- | ---------------------------- |
| **`@counter-style`** | `CounterStyle` | `CounterStyleHyphen` | `CounterStyleFallback` | `CounterStyleHyphenFallback` |
| **`@font-face`** | `FontFace` | `FontFaceHyphen` | `FontFaceFallback` | `FontFaceHyphenFallback` |
| **`@viewport`** | `Viewport` | `ViewportHyphen` | `ViewportFallback` | `ViewportHyphenFallback` |
## Pseudo types
String literals of pseudo classes and pseudo elements
- `Pseudos`
Extends:
- `AdvancedPseudos`
Function-like pseudos e.g. `:not(:first-child)`. The string literal contains the value excluding the parenthesis: `:not`. These are separated because they require an argument that results in infinite number of variations.
- `SimplePseudos`
Plain pseudos e.g. `:hover` that can only be **one** variation.
## Generics
All interfaces has two optional generic argument to define length and time: `CSS.Properties<TLength = string | 0, TTime = string>`
- **Length** is the first generic parameter and defaults to `string | 0` because `0` is the only [length where the unit identifier is optional](https://drafts.csswg.org/css-values-3/#lengths). You can specify this, e.g. `string | number`, for platforms and libraries that accepts any numeric value as length with a specific unit.
```tsx
const style: CSS.Properties<string | number> = {
width: 100,
};
```
- **Time** is the second generic argument and defaults to `string`. You can specify this, e.g. `string | number`, for platforms and libraries that accepts any numeric value as length with a specific unit.
```tsx
const style: CSS.Properties<string | number, number> = {
transitionDuration: 1000,
};
```
## Usage
```ts
import type * as CSS from 'csstype';
const style: CSS.Properties = {
width: '10px',
margin: '1em',
};
```
In some cases, like for CSS-in-JS libraries, an array of values is a way to provide fallback values in CSS. Using `CSS.PropertiesFallback` instead of `CSS.Properties` will add the possibility to use any property value as an array of values.
```ts
import type * as CSS from 'csstype';
const style: CSS.PropertiesFallback = {
display: ['-webkit-flex', 'flex'],
color: 'white',
};
```
There's even string literals for pseudo selectors and elements.
```ts
import type * as CSS from 'csstype';
const pseudos: { [P in CSS.SimplePseudos]?: CSS.Properties } = {
':hover': {
display: 'flex',
},
};
```
Hyphen cased (kebab cased) properties are provided in `CSS.PropertiesHyphen` and `CSS.PropertiesHyphenFallback`. It's not **not** added by default in `CSS.Properties`. To allow both of them, you can simply extend with `CSS.PropertiesHyphen` or/and `CSS.PropertiesHyphenFallback`.
```ts
import type * as CSS from 'csstype';
interface Style extends CSS.Properties, CSS.PropertiesHyphen {}
const style: Style = {
'flex-grow': 1,
'flex-shrink': 0,
'font-weight': 'normal',
backgroundColor: 'white',
};
```
Adding type checked CSS properties to a `HTMLElement`.
```ts
import type * as CSS from 'csstype';
const style: CSS.Properties = {
color: 'red',
margin: '1em',
};
let button = document.createElement('button');
Object.assign(button.style, style);
```
## What should I do when I get type errors?
The goal is to have as perfect types as possible and we're trying to do our best. But with CSS Custom Properties, the CSS specification changing frequently and vendors implementing their own specifications with new releases sometimes causes type errors even if it should work. Here's some steps you could take to get it fixed:
_If you're using CSS Custom Properties you can step directly to step 3._
1. **First of all, make sure you're doing it right.** A type error could also indicate that you're not :wink:
- Some CSS specs that some vendors has implemented could have been officially rejected or haven't yet received any official acceptance and are therefor not included
- If you're using TypeScript, [type widening](https://blog.mariusschulz.com/2017/02/04/TypeScript-2-1-literal-type-widening) could be the reason you get `Type 'string' is not assignable to...` errors
2. **Have a look in [issues](https://github.com/frenic/csstype/issues) to see if an issue already has been filed. If not, create a new one.** To help us out, please refer to any information you have found.
3. Fix the issue locally with **TypeScript** (Flow further down):
- The recommended way is to use **module augmentation**. Here's a few examples:
```ts
// My css.d.ts file
import type * as CSS from 'csstype';
declare module 'csstype' {
interface Properties {
// Add a missing property
WebkitRocketLauncher?: string;
// Add a CSS Custom Property
'--theme-color'?: 'black' | 'white';
// Allow namespaced CSS Custom Properties
[index: `--theme-${string}`]: any;
// Allow any CSS Custom Properties
[index: `--${string}`]: any;
// ...or allow any other property
[index: string]: any;
}
}
```
- The alternative way is to use **type assertion**. Here's a few examples:
```ts
const style: CSS.Properties = {
// Add a missing property
['WebkitRocketLauncher' as any]: 'launching',
// Add a CSS Custom Property
['--theme-color' as any]: 'black',
};
```
Fix the issue locally with **Flow**:
- Use **type assertion**. Here's a few examples:
```js
const style: $Exact<CSS.Properties<*>> = {
// Add a missing property
[('WebkitRocketLauncher': any)]: 'launching',
// Add a CSS Custom Property
[('--theme-color': any)]: 'black',
};
```
## Version 3.2
- **No longer compatible with version 2**
Conflicts may occur when both version ^3.2.0 and ^2.0.0 are installed. Potential fix for Npm would be to force resolution in `package.json`:
```json
{
"overrides": {
"csstype": "^3.2.0"
}
}
```
## Version 3.1
- **Data types are exposed**
TypeScript: `DataType.Color`
Flow: `DataType$Color`
## Version 3.0
- **All property types are exposed with namespace**
TypeScript: `Property.AlignContent` (was `AlignContentProperty` before)
Flow: `Property$AlignContent`
- **All at-rules are exposed with namespace**
TypeScript: `AtRule.FontFace` (was `FontFace` before)
Flow: `AtRule$FontFace`
- **Data types are NOT exposed**
E.g. `Color` and `Box`. Because the generation of data types may suddenly be removed or renamed.
- **TypeScript hack for autocompletion**
Uses `(string & {})` for literal string unions and `(number & {})` for literal number unions ([related issue](https://github.com/microsoft/TypeScript/issues/29729)). Utilize `PropertyValue<T>` to unpack types from e.g. `(string & {})` to `string`.
- **New generic for time**
Read more on the ["Generics"](#generics) section.
- **Flow types improvements**
Flow Strict enabled and exact types are used.
## Contributing
**Never modify `index.d.ts` and `index.js.flow` directly. They are generated automatically and committed so that we can easily follow any change it results in.** Therefor it's important that you run `$ git config merge.ours.driver true` after you've forked and cloned. That setting prevents merge conflicts when doing rebase.
### Commands
- `npm run build` Generates typings and type checks them
- `npm run watch` Runs build on each save
- `npm run test` Runs the tests
- `npm run lazy` Type checks, lints and formats everything
-22569
View File
File diff suppressed because it is too large Load Diff
-6863
View File
File diff suppressed because it is too large Load Diff
-70
View File
@@ -1,70 +0,0 @@
{
"name": "csstype",
"version": "3.2.3",
"main": "",
"types": "index.d.ts",
"description": "Strict TypeScript and Flow types for style based on MDN data",
"repository": "https://github.com/frenic/csstype",
"author": "Fredrik Nicol <fredrik.nicol@gmail.com>",
"license": "MIT",
"devDependencies": {
"@babel/core": "^7.28.5",
"@babel/preset-env": "^7.28.5",
"@babel/preset-typescript": "^7.28.5",
"@eslint/js": "^9.39.1",
"@mdn/browser-compat-data": "7.1.21",
"@tsconfig/node24": "^24.0.2",
"@types/chokidar": "^2.1.7",
"@types/css-tree": "^2.3.11",
"@types/jest": "^30.0.0",
"@types/jsdom": "^27.0.0",
"@types/node": "^24.10.1",
"@types/prettier": "^3.0.0",
"@types/turndown": "^5.0.6",
"babel-jest": "^30.2.0",
"chalk": "^5.6.2",
"chokidar": "^4.0.3",
"css-tree": "^3.1.0",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-prettier": "^5.5.4",
"flow-bin": "^0.291.0",
"jest": "^30.2.0",
"jsdom": "^27.2.0",
"mdn-data": "2.25.0",
"prettier": "^3.6.2",
"release-it": "^19.0.6",
"tsx": "^4.20.6",
"turndown": "^7.2.2",
"typescript": "~5.9.3",
"typescript-eslint": "^8.46.4"
},
"overrides": {
"js-yaml": ">=4.1.1"
},
"scripts": {
"prepublish": "npm install --no-save --prefix __tests__ && npm install --no-save --prefix __tests__/__fixtures__",
"release": "release-it",
"update": "tsx update.ts",
"build": "tsx --inspect build.ts --start",
"watch": "tsx build.ts --watch",
"lint": "eslint . --ext .js,.jsx,.ts,.tsx --fix",
"pretty": "prettier --write build.ts **/*.{ts,js,json,md}",
"lazy": "tsc && npm run lint",
"test": "jest --runInBand",
"test:src": "jest src.*.ts",
"test:dist": "jest dist.*.ts --runInBand"
},
"files": [
"index.d.ts",
"index.js.flow"
],
"keywords": [
"css",
"style",
"typescript",
"flow",
"typings",
"types",
"definitions"
]
}
-22
View File
@@ -1,22 +0,0 @@
The MIT License (MIT)
Copyright (c) 2015 EOX IT Services GmbH
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-794
View File
@@ -1,794 +0,0 @@
# geotiff.js
[![Node.js CI](https://github.com/geotiffjs/geotiff.js/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/geotiffjs/geotiff.js/actions/workflows/ci.yml) [![npm version](https://badge.fury.io/js/geotiff.svg)](https://badge.fury.io/js/geotiff) [![Gitter chat](https://badges.gitter.im/geotiffjs/geotiff.js.png)](https://gitter.im/geotiffjs/Lobby)
Read (geospatial) metadata and raw array data from a wide variety of different
(Geo)TIFF files types.
## Features
Currently available functionality:
* Parsing TIFFs from various sources:
* remote (via `fetch` or XHR)
* from a local `ArrayBuffer`
* from the filesystem (on Browsers using the `FileReader` and on node using the filesystem functions)
* Parsing the headers of all possible TIFF files
* Rudimentary extraction of geospatial metadata
* Reading raster data from:
* stripped images
* tiled images
* band interleaved images
* pixel interleaved images
* Supported data-types:
* (U)Int8/16/32
* UInt1-31 (with some drawbacks)
* Float16/32/64
* Enabled compressions:
* no compression
* Packbits
* LZW
* Deflate (with floating point or horizontal predictor support)
* JPEG
* LERC (with additional Deflate compression support)
* Zstandard
* image formats supported via the browser (such as WebP)
* Automatic selection of overview level to read from
* Subsetting via an image window or bounding box and selected bands
* Reading of samples into separate arrays or a single pixel-interleaved array
* Configurable tile/strip cache
* Configurable Pool of workers to increase decoding efficiency
* Utility functions for geospatial parameters (Bounding Box, Origin, Resolution)
* Limited [bigTIFF](http://bigtiff.org/#FILE_FORMAT) support
* Automated testing via PhantomJS
Further documentation can be found [here](https://geotiffjs.github.io/geotiff.js/).
## Example Usage
Geotiff gives you access to all GeoTIFF metadata, but does not offer any one specific higher level API (such as GDAL) for things like transforms or data extraction. However, you can write your own higher level API using this library, given your specific dataset needs.
As an example, here is how you would resolve GPS coordinates to elevation in a GeoTIFF that encodes WGS-84 compliant geo data:
```js
import { fromUrl, fromArrayBuffer, fromBlob } from "geotiff";
const lerp = (a, b, t) => (1 - t) * a + t * b;
function transform(a, b, M, roundToInt = false) {
const round = (v) => (roundToInt ? v | 0 : v);
return [
round(M[0] + M[1] * a + M[2] * b),
round(M[3] + M[4] * a + M[5] * b),
];
}
// Load our data tile from url, arraybuffer, or blob, so we can work with it:
const tiff = await fromArrayBuffer(...);
const image = await tiff.getImage(); // by default, the first image is read.
// Construct the WGS-84 forward and inverse affine matrices:
const s = image.fileDirectory.getValue('ModelPixelScale');
const t = image.fileDirectory.getValue('ModelTiepoint');
let [sx, sy, sz] = s;
let [px, py, k, gx, gy, gz] = t;
sy = -sy; // WGS-84 tiles have a "flipped" y component
const pixelToGPS = [gx, sx, 0, gy, 0, sy];
console.log(`pixel to GPS transform matrix:`, pixelToGPS);
const gpsToPixel = [-gx / sx, 1 / sx, 0, -gy / sy, 0, 1 / sy];
console.log(`GPS to pixel transform matrix:`, gpsToPixel);
// Convert a GPS coordinate to a pixel coordinate in our tile:
const [gx1, gy1, gx2, gy2] = image.getBoundingBox();
const lat = lerp(gy1, gy2, Math.random());
const long = lerp(gx1, gx2, Math.random());
console.log(`Looking up GPS coordinate (${lat.toFixed(6)},${long.toFixed(6)})`);
const [x, y] = transform(long, lat, gpsToPixel, true);
console.log(`Corresponding tile pixel coordinate: [${x}][${y}]`);
// And as each pixel in the tile covers a geographic area, not a single
// GPS coordinate, get the area that this pixel covers:
const gpsBBox = [transform(x, y, pixelToGPS), transform(x + 1, y + 1, pixelToGPS)];
console.log(`Pixel covers the following GPS area:`, gpsBBox);
// Finally, retrieve the elevation associated with this pixel's geographic area:
const rasters = await image.readRasters();
const { width, [0]: raster } = rasters;
const elevation = raster[x + y * width];
console.log(`The elevation at (${lat.toFixed(6)},${long.toFixed(6)}) is ${elevation}m`);
```
## Advanced Example Usage
For more advanced examples of `geotiff` in larger codebases, please have a look at the following projects:
* [Slice view using Cesium.js (TAMP project)](http://www.youtube.com/watch?v=E6kFLtKgeJ8)
[![3D slice view](http://img.youtube.com/vi/E6kFLtKgeJ8/0.jpg)](http://www.youtube.com/watch?v=E6kFLtKgeJ8)
* [Contour generation using d3-contour](https://bl.ocks.org/mbostock/83c0be21dba7602ee14982b020b12f51)
[![contour](https://user-images.githubusercontent.com/482265/112866402-0b219880-90ba-11eb-9dda-5f1d9ed9bafc.jpg)](https://bl.ocks.org/mbostock/83c0be21dba7602ee14982b020b12f51)
## Migration Guide (v2 to v3)
Version 3.0 introduces significant performance improvements through deferred tag reading, but includes breaking changes to some APIs. This guide will help you migrate your code.
### Summary of Changes
**For most users**: Minimal changes required. The high-level APIs (`getImage()`, `readRasters()`, etc.) remain compatible. You'll mainly need to:
- Add `await` to `getTiePoints()` and `getGDALMetadata()`
- Change `image.geoKeys` to `image.getGeoKeys()`
**For advanced users**: If you directly access `fileDirectory` properties, you'll need to migrate to the new `ImageFileDirectory` methods.
### Breaking Changes
#### 1. GeoKeys Access
**Before (v2)**:
```javascript
const image = await tiff.getImage();
const geoKeys = image.geoKeys;
```
**After (v3)**:
```javascript
const image = await tiff.getImage();
const geoKeys = image.getGeoKeys();
```
#### 2. getTiePoints() and getGDALMetadata() are now async
**Before (v2)**:
```javascript
const tiePoints = image.getTiePoints();
const metadata = image.getGDALMetadata();
```
**After (v3)**:
```javascript
const tiePoints = await image.getTiePoints();
const metadata = await image.getGDALMetadata();
```
#### 3. Accessing fileDirectory properties
The `fileDirectory` object has been replaced with an `ImageFileDirectory` class that supports deferred loading.
**Before (v2)**:
```javascript
const image = await tiff.getImage();
const { ModelPixelScale: s, ModelTiepoint: t } = image.fileDirectory;
const width = image.fileDirectory.ImageWidth;
const compression = image.fileDirectory.Compression;
```
**After (v3)** - Use `getValue()` for synchronous access:
```javascript
const image = await tiff.getImage();
const s = image.fileDirectory.getValue('ModelPixelScale');
const t = image.fileDirectory.getValue('ModelTiepoint');
const width = image.fileDirectory.getValue('ImageWidth');
const compression = image.fileDirectory.getValue('Compression');
```
**Note**: `getValue()` throws an error if the tag is deferred. For tags that might be deferred (like large arrays), use `loadValue()`:
```javascript
const colorMap = await image.fileDirectory.loadValue('ColorMap');
```
#### 4. Checking if tags exist
**Before (v2)**:
```javascript
if (image.fileDirectory.ModelTiepoint) {
// ...
}
```
**After (v3)**:
```javascript
if (image.fileDirectory.hasTag('ModelTiepoint')) {
// ...
}
```
#### 5. Accessing array elements
For large arrays (like `TileOffsets`, `StripOffsets`), individual elements can now be loaded on-demand:
**Before (v2)**:
```javascript
const offset = image.fileDirectory.TileOffsets[5];
```
**After (v3)**:
```javascript
const offset = await image.fileDirectory.loadValueIndexed('TileOffsets', 5);
```
#### 6. Pool API changes
If you're using the `Pool` class directly (most users don't):
**Before (v2)**:
```javascript
const pool = new GeoTIFF.Pool();
const decoded = await pool.decode(fileDirectory, buffer);
```
**After (v3)**:
```javascript
const pool = new GeoTIFF.Pool();
const compression = fileDirectory.getValue('Compression');
const params = await getDecoderParameters(compression, fileDirectory);
const boundPool = pool.bindParameters(compression, params);
const decoded = await boundPool.decode(buffer);
```
**Note**: When using `readRasters({ pool })`, this is handled automatically.
#### 7. Custom Decoders
If you've implemented custom decoders:
**Before (v2)**:
```javascript
class MyDecoder extends BaseDecoder {
async decode(fileDirectory, buffer) {
// decode using fileDirectory properties
}
}
```
**After (v3)**:
```javascript
class MyDecoder extends BaseDecoder {
constructor(parameters) {
super(parameters);
// parameters extracted once during construction
}
async decode(buffer) {
// decode using this.parameters
}
}
// Register with parameter extraction function
addDecoder(
12345, // compression ID
() => import('./mydecoder.js').then(m => m.default),
async (fileDirectory) => {
return {
...await defaultDecoderParameterFn(fileDirectory),
myCustomParam: await fileDirectory.loadValue('MyCustomTag')
};
}
);
```
### Migration Examples
#### Example 1: Reading with ModelTiepoint/ModelPixelScale
**Before (v2)**:
```javascript
const tiff = await fromUrl(url);
const image = await tiff.getImage();
const { ModelPixelScale: s, ModelTiepoint: t } = image.fileDirectory;
const [sx, sy, sz] = s;
const [px, py, k, gx, gy, gz] = t;
```
**After (v3)**:
```javascript
const tiff = await fromUrl(url);
const image = await tiff.getImage();
const s = image.fileDirectory.getValue('ModelPixelScale');
const t = image.fileDirectory.getValue('ModelTiepoint');
const [sx, sy, sz] = s;
const [px, py, k, gx, gy, gz] = t;
```
#### Example 2: Working with ColorMap (potentially deferred)
**Before (v2)**:
```javascript
const image = await tiff.getImage();
const colorMap = image.fileDirectory.ColorMap;
```
**After (v3)**:
```javascript
const image = await tiff.getImage();
const colorMap = await image.fileDirectory.loadValue('ColorMap');
```
#### Example 3: Checking PhotometricInterpretation
**Before (v2)**:
```javascript
const pi = image.fileDirectory.PhotometricInterpretation;
if (pi === photometricInterpretations.RGB) {
// ...
}
```
**After (v3)**:
```javascript
const pi = image.fileDirectory.getValue('PhotometricInterpretation');
if (pi === photometricInterpretations.RGB) {
// ...
}
```
### What Hasn't Changed
These APIs remain fully backwards compatible:
```javascript
// GeoTIFF class
const tiff = await fromUrl(url);
const tiff = await fromArrayBuffer(buffer);
const tiff = await fromBlob(blob);
const imageCount = await tiff.getImageCount();
const image = await tiff.getImage(index);
// GeoTIFFImage class
const width = image.getWidth();
const height = image.getHeight();
const samplesPerPixel = image.getSamplesPerPixel();
const tileWidth = image.getTileWidth();
const tileHeight = image.getTileHeight();
const origin = image.getOrigin();
const resolution = image.getResolution();
const bbox = image.getBoundingBox();
// Reading raster data
const data = await image.readRasters({ window, samples, interleave, pool });
const rgb = await image.readRGB({ window });
// Writing GeoTIFFs
const arrayBuffer = await writeArrayBuffer(values, metadata);
```
### Performance Benefits
The new deferred loading system provides significant performance improvements:
- **Faster initial parsing**: Large arrays (like tile offsets) are not loaded upfront
- **Reduced memory usage**: Only load the data you actually need
- **On-demand array access**: Access individual array elements without loading the entire array
- **Backward compatible caching**: Frequently accessed tags are eagerly loaded by default
## Setup
To setup the repository do the following steps:
```bash
# clone repo
git clone https://github.com/constantinius/geotiff.js.git
cd geotiff.js/
# install development dependencies
npm install
```
## Testing and Building
In order to run the tests you first have to set up the test data. This requires
the [GDAL](http://gdal.org/) and [ImageMagick](http://imagemagick.org/) tools.
Installation of these tools varies according to the operating system, the
following listing shows the installation on Ubuntu (using the ubuntugis-unstable
repository):
```bash
sudo add-apt-repository -y ppa:ubuntugis/ubuntugis-unstable
sudo apt-get update
sudo apt-get install -y gdal-bin imagemagick
```
To install GDAL and ImageMagick on MacOS X, please use [Homebrew](https://brew.sh/). The setup script also needs `wget` on MacOS X
```bash
brew install wget gdal imagemagick
```
When GDAL and ImageMagick is installed, the test data setup script can be run:
```bash
cd test/data
sh setup_data.sh
cd -
```
To test the library (using PhantomJS, karma, mocha and chai) do the following:
```bash
npm test
```
To do some in-browser testing do:
```bash
npm run dev
```
and navigate to `http://localhost:8090/test/`
To build the library do:
```bash
npm run build
```
The output is written to `dist-browser/main.js` and `dist-node/main.js`.
## Install
You can install geotiff.js using npm:
```
npm install geotiff
```
or you can use the prebuilt version with a CDN:
```html
<script src="https://cdn.jsdelivr.net/npm/geotiff"></script>
```
## Usage
geotiff.js works with both `require`, `import` and the global variable `GeoTIFF`:
```javascript
const GeoTIFF = require('geotiff');
const { fromUrl, fromUrls, fromArrayBuffer, fromBlob } = GeoTIFF;
// or
import GeoTIFF, { fromUrl, fromUrls, fromArrayBuffer, fromBlob } from 'geotiff';
```
or:
```html
<script src="https://cdn.jsdelivr.net/npm/geotiff"></script>
<script>
console.log(GeoTIFF);
</script>
```
To parse a GeoTIFF, first a data source is required. To help with the development,
there are shortcuts available. The following creates a source that reads from a
remote GeoTIFF referenced by a URL:
```javascript
fromUrl(someUrl)
.then(tiff => { /* ... */});
// or when using async/await
(async function() {
const tiff = await fromUrl(someUrl);
// ...
})()
```
Note: the interactions with geotiff.js objects are oftentimes asynchronous. For
the sake of brevity we will only show the async/await syntax and not the
`Promise` based one in the following examples.
Accessing remote images is just one way to open TIFF images with geotiff.js. Other
options are reading from a local `ArrayBuffer`:
```javascript
// using local ArrayBuffer
const response = await fetch(someUrl);
const arrayBuffer = await response.arrayBuffer();
const tiff = await fromArrayBuffer(arrayBuffer);
```
or a `Blob`/`File`:
```html
<input type="file" id="file">
<script>
const input = document.getElementById('file');
input.onchange = async function() {
const tiff = await fromBlob(input.files[0]);
}
</script>
```
Now that we have opened the TIFF file, we can inspect it. The TIFF is structured
in a small header and a list of one or more images (Image File Directory, IFD to
use the TIFF nomenclature). To get one image by index the `getImage()` function
must be used. This is again an asynchronous operation, as the IFDs are loaded
lazily:
```javascript
const image = await tiff.getImage(); // by default, the first image is read.
```
Now that we have obtained a `GeoTIFFImage` object we can inspect its metadata
(like size, tiling, number of samples, geographical information, etc.). All
the metadata is parsed once the IFD is first parsed, thus the access to that
is synchronous:
```javascript
const width = image.getWidth();
const height = image.getHeight();
const tileWidth = image.getTileWidth();
const tileHeight = image.getTileHeight();
const samplesPerPixel = image.getSamplesPerPixel();
// when we are actually dealing with geo-data the following methods return
// meaningful results:
const origin = image.getOrigin();
const resolution = image.getResolution();
const bbox = image.getBoundingBox();
```
The actual raster data is not fetched and parsed automatically. This is because
it is usually much more spacious and the decoding of the pixels can be time
consuming due to the necessity of decompression.
To read a whole image into one big array of arrays the following method call can be used:
```javascript
const data = await image.readRasters();
```
For convenience the result always has a `width` and `height` attribute:
```javascript
const data = await image.readRasters();
const { width, height } = data;
```
By default, the raster is split to a separate array for each component. For an RGB image
for example, we'd get three arrays, one for red, green and blue.
```javascript
const [red, green, blue] = await image.readRasters();
```
If we want instead all the bands interleaved in one big array, we have to pass the
`interleave: true` option:
```javascript
const [r0, g0, b0, r1, g1, b1, ...] = await image.readRasters({ interleave: true });
```
If we are only interested in a specific region of the image, the `window` option can be
used to limit reading in that bounding box. Note: the bounding box is in 'image coordinates'
not geographical ones:
```javascript
const left = 50;
const top = 10;
const right = 150;
const bottom = 60;
const data = await image.readRasters({ window: [left, top, right, bottom] });
```
This image window can go beyond the image bounds. In that case it might be usefull to supply
a `fillValue: value` option (can also be an array, one value for each sample).
It is also possible to just read specific samples for each pixel. For example, we can only
read the red component from an RGB image:
```javascript
const [red] = await image.readRasters({ samples: [0] });
```
When you want your output in a specific size, you can use the `width` and `height` options.
This defaults of course to the size of your supplied `window` or the image size if no
`window` was supplied.
As the data now needs to be resampled, a `resampleMethod` can be specified. This defaults to
the nearest neighbour method, but also the `'bilinear'` method is supported:
```javascript
const data = await image.readRasters({ width: 40, height: 40, resampleMethod: 'bilinear' });
```
### Using decoder pools to improve parsing performance
Decoding compressed images can be a time consuming process. To minimize this
geotiff.js provides the `Pool` mechanism which uses WebWorkers to split the amount
of work on multiple 'threads'.
```javascript
const pool = new GeoTIFF.Pool();
const data = await image.readRasters({ pool });
```
It is possible to provide a pool size (i.e: number of workers), by default the number
of available processors is used.
### Dealing with visual data
The TIFF specification provides various ways to encode visual data. In the
specification this is called photometric interpretation. The simplest case we
already dealt with is the RGB one. Others are grayscale, paletted images, CMYK,
YCbCr, and CIE L*a*b.
geotiff.js provides a method to automatically convert these images to RGB:
`readRGB()`. This method is very similar to the `readRasters` method with
the distinction that the `interleave` option now defaults to `true` and the
`samples` are automatically chosen.
```javascript
const rgb = await image.readRGB({
// options...
});
```
### Automatic image selection (experimental)
When dealing with images that have internal (or even external, see the next section)
overviews, `GeoTIFF` objects provide a separate `readRasters` method. This method
works very similar to the method on the `GeoTIFFImage` objects with the same name.
By default, it uses the larges image available (highest resolution), but when either
`width`, `height`, `resX`, or `resY` are specified, then the best fitting image will
be used for reading.
Additionally, it allows the `bbox` instead of the `window` parameter. This works
similarly, but uses geographic coordinates instead of pixel ones.
```javascript
const data = await tiff.readRasters({
bbox: [10.34, 57.28, 13.34, 60.23],
resX: 0.1,
resY: 0.1
});
```
### External overviews
Especially for certain kinds of high resolution images it is not uncommon to separate
the highest resolution from the lower resolution overviews (usually using the `.ovr`
extension). With geotiff.js it is possible to use files of this setup, just as you
would use single-file images by taking advantage of the `MultiGeoTIFF` objects. They
behave exactly the same as the before mentioned `GeoTIFF` objects: you can select
images by index or read data using `readRasters`. Toget such a file use the `fromUrls`
factory function:
```javascript
const multiTiff = await fromUrls(
'LC08_L1TP_189027_20170403_20170414_01_T1_B3.TIF',
['LC08_L1TP_189027_20170403_20170414_01_T1_B3.TIF.ovr']
);
```
### AbortController Support
Geotiff.js supports the use of [`AbortController`s](https://developer.mozilla.org/en-US/docs/Web/API/AbortController). Calls to `getRasters`, `readRGB` and `getTileOrStrip` will throw an `Error` with name `AbortSignal` similar to the browser's `fetch` behavior.
```javascript
const tiff = await fromUrl(source);
const abortController = new AbortController();
const { signal } = abortController;
abortController.abort();
try {
const data = await tiff.readRasters({ signal });
} catch(e) {
if (err.name === 'AbortError') {
// do stuff
}
}
```
### Writing GeoTIFFs (Beta Version)
You can create a binary representation of a GeoTIFF using `writeArrayBuffer`.
This function returns an ArrayBuffer which you can then save as a .tif file.
:warning: writeArrayBuffer currently writes the values uncompressed
```javascript
import GeoTIFF, { writeArrayBuffer } from 'geotiff';
const values = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const metadata = {
height: 3,
width: 3
};
const arrayBuffer = await writeArrayBuffer(values, metadata);
```
You can also customize the metadata using names found in the [TIFF Spec](https://www.loc.gov/preservation/digital/formats/content/tiff_tags.shtml) and [GeoTIFF spec](https://cdn.earthdata.nasa.gov/conduit/upload/6852/geotiff-1.8.1-1995-10-31.pdf).
```javascript
import { writeArrayBuffer } from 'geotiff';
const values = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const metadata = {
GeographicTypeGeoKey: 4326,
height: 3,
ModelPixelScale: [0.031355, 0.031355, 0],
ModelTiepoint: [0, 0, 0, 11.331755000000001, 46.268645, 0],
width: 3
};
const arrayBuffer = await writeArrayBuffer(values, metadata);
```
## What to do with the data?
There is a nice HTML 5/WebGL based rendering library called
[plotty](https://github.com/santilland/plotty), that allows for some really nice
on the fly rendering of the data contained in a GeoTIFF.
```html
<canvas id="plot"></canvas>
<script>
// ...
(async function() {
const tiff = await fromUrl(url);
const image = await tiff.getImage();
const data = await image.readRasters();
const canvas = document.getElementById("plot");
const plot = new plotty.plot({
canvas,
data: data[0],
width: image.getWidth(),
height: image.getHeight(),
domain: [0, 256],
colorScale: "viridis"
});
plot.render();
})();
</script>
```
There's also a library called [geotiff-geokeys-to-proj4](https://github.com/matafokka/geotiff-geokeys-to-proj4), that allows for reprojecting pixel coordinates and, therefore, consuming geospatial data contained in GeoTIFF.
## BigTIFF support
geotiff.js has a limited support for files in the BigTIFF format. The limitations
originate in the capabilities of current JavaScript implementations regarding
64 bit integer parsers and structures: there are no functions to read 64 bit
integers from a stream and no such typed arrays. As BigTIFF relies on 64 bit
offsets and also allows tag values of those types. In order to still provide
a reasonable support, the following is implemented:
* 64 bit integers are read as two 32 bit integers and then combined. As
numbers in JavaScript are typically implemented as 64 bit floats, there
might be inaccuracies for *very* large values.
* For 64 bit integer arrays, the default `Array` type is used. This might
cause problems for some compression algorithms if those arrays are used for
pixel values.
## n-bit Support
geotiff.js has some n-bit support which means that it supports unsigned integer
data reading with each element using a non-multiple of 8 bit depth. This only
works with band interleaved images (see
[this related issue](https://github.com/geotiffjs/geotiff.js/issues/202)).
## Planned stuff:
* Better support of geospatial parameters:
* WKT representation
## Known Issues
The open issues can be found on [GitHub](https://github.com/geotiffjs/geotiff.js/issues).
## Contribution
If you have an idea, found a bug or have a remark, please open a ticket, we will
look into it ASAP.
Pull requests are welcome as well!
## Community Packages
A list of community packages can be found in [COMMUNITY.md](COMMUNITY.md)
## Acknowledgements
This library was inspired by
[GeotiffParser](https://github.com/xlhomme/GeotiffParser.js). It provided a
great starting point, but lacked the capabilities to read the raw raster data
which is the aim of geotiff.js.
-5
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
-36
View File
@@ -1,36 +0,0 @@
/**
* @typedef {Object} BaseDecoderParameters
* @property {number} tileWidth
* @property {number} tileHeight
* @property {number} predictor
* @property {number|number[]|import('../geotiff.js').TypedArray} bitsPerSample
* @property {number} planarConfiguration
* @property {number} [samplesPerPixel]
*/
export default class BaseDecoder {
/**
* @param {BaseDecoderParameters} parameters
*/
constructor(parameters: BaseDecoderParameters);
parameters: BaseDecoderParameters;
/**
* @abstract
* @param {ArrayBufferLike} _buffer
* @returns {Promise<ArrayBufferLike>|ArrayBufferLike}
*/
decodeBlock(_buffer: ArrayBufferLike): Promise<ArrayBufferLike> | ArrayBufferLike;
/**
* @param {ArrayBufferLike} buffer
* @returns {Promise<ArrayBufferLike>}
*/
decode(buffer: ArrayBufferLike): Promise<ArrayBufferLike>;
}
export type BaseDecoderParameters = {
tileWidth: number;
tileHeight: number;
predictor: number;
bitsPerSample: number | number[] | import("../geotiff.js").TypedArray;
planarConfiguration: number;
samplesPerPixel?: number | undefined;
};
//# sourceMappingURL=basedecoder.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"basedecoder.d.ts","sourceRoot":"","sources":["../../src/compression/basedecoder.js"],"names":[],"mappings":"AAEA;;;;;;;;GAQG;AAEH;IACE;;OAEG;IACH,wBAFW,qBAAqB,EAI/B;IADC,kCAA4B;IAG9B;;;;OAIG;IACH,qBAHW,eAAe,GACb,OAAO,CAAC,eAAe,CAAC,GAAC,eAAe,CAIpD;IAED;;;OAGG;IACH,eAHW,eAAe,GACb,OAAO,CAAC,eAAe,CAAC,CAiBpC;CACF;;eA7Ca,MAAM;gBACN,MAAM;eACN,MAAM;mBACN,MAAM,GAAC,MAAM,EAAE,GAAC,OAAO,eAAe,EAAE,UAAU;yBAClD,MAAM"}
-41
View File
@@ -1,41 +0,0 @@
import { applyPredictor } from '../predictor.js';
/**
* @typedef {Object} BaseDecoderParameters
* @property {number} tileWidth
* @property {number} tileHeight
* @property {number} predictor
* @property {number|number[]|import('../geotiff.js').TypedArray} bitsPerSample
* @property {number} planarConfiguration
* @property {number} [samplesPerPixel]
*/
export default class BaseDecoder {
/**
* @param {BaseDecoderParameters} parameters
*/
constructor(parameters) {
this.parameters = parameters;
}
/**
* @abstract
* @param {ArrayBufferLike} _buffer
* @returns {Promise<ArrayBufferLike>|ArrayBufferLike}
*/
decodeBlock(_buffer) {
throw new Error('decodeBlock not implemented');
}
/**
* @param {ArrayBufferLike} buffer
* @returns {Promise<ArrayBufferLike>}
*/
async decode(buffer) {
const decoded = await this.decodeBlock(buffer);
const { tileWidth, tileHeight, predictor, bitsPerSample, planarConfiguration, } = this.parameters;
if (predictor !== 1) {
const isBitsPerSampleArray = Array.isArray(bitsPerSample) || ArrayBuffer.isView(bitsPerSample);
const adaptedBitsPerSample = isBitsPerSampleArray ? Array.from(bitsPerSample) : [bitsPerSample];
return applyPredictor(decoded, predictor, tileWidth, tileHeight, adaptedBitsPerSample, planarConfiguration);
}
return decoded;
}
}
//# sourceMappingURL=basedecoder.js.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"basedecoder.js","sourceRoot":"","sources":["../../src/compression/basedecoder.js"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAEjD;;;;;;;;GAQG;AAEH,MAAM,CAAC,OAAO,OAAO,WAAW;IAC9B;;OAEG;IACH,YAAY,UAAU;QACpB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC/B,CAAC;IAED;;;;OAIG;IACH,WAAW,CAAC,OAAO;QACjB,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC;IACjD,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,MAAM,CAAC,MAAM;QACjB,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;QAE/C,MAAM,EACJ,SAAS,EAAE,UAAU,EAAE,SAAS,EAAE,aAAa,EAAE,mBAAmB,GACrE,GAAG,IAAI,CAAC,UAAU,CAAC;QACpB,IAAI,SAAS,KAAK,CAAC,EAAE,CAAC;YACpB,MAAM,oBAAoB,GAAG,KAAK,CAAC,OAAO,CAAC,aAAa,CAAC,IAAI,WAAW,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;YAC/F,MAAM,oBAAoB,GAAG,oBAAoB,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC;YAChG,OAAO,cAAc,CACnB,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,UAAU,EAAE,oBAAoB,EAC/D,mBAAmB,CACpB,CAAC;QACJ,CAAC;QACD,OAAO,OAAO,CAAC;IACjB,CAAC;CACF"}
-6
View File
@@ -1,6 +0,0 @@
export default class DeflateDecoder extends BaseDecoder {
/** @param {ArrayBuffer} buffer */
decodeBlock(buffer: ArrayBuffer): ArrayBuffer;
}
import BaseDecoder from './basedecoder.js';
//# sourceMappingURL=deflate.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"deflate.d.ts","sourceRoot":"","sources":["../../src/compression/deflate.js"],"names":[],"mappings":"AAGA;IACE,kCAAkC;IAClC,oBADY,WAAW,eAGtB;CACF;wBAPuB,kBAAkB"}
-9
View File
@@ -1,9 +0,0 @@
import { inflate } from 'pako';
import BaseDecoder from './basedecoder.js';
export default class DeflateDecoder extends BaseDecoder {
/** @param {ArrayBuffer} buffer */
decodeBlock(buffer) {
return inflate(new Uint8Array(buffer)).buffer;
}
}
//# sourceMappingURL=deflate.js.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"deflate.js","sourceRoot":"","sources":["../../src/compression/deflate.js"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAC/B,OAAO,WAAW,MAAM,kBAAkB,CAAC;AAE3C,MAAM,CAAC,OAAO,OAAO,cAAe,SAAQ,WAAW;IACrD,kCAAkC;IAClC,WAAW,CAAC,MAAM;QAChB,OAAO,OAAO,CAAC,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC;IAChD,CAAC;CACF"}
-35
View File
@@ -1,35 +0,0 @@
/**
* Register a decoder for a specific compression method or a range of compressions
* @param {(number|undefined|(number|undefined)[])} cases ids of the compression methods to register for
* @param {function():Promise<typeof BaseDecoder>} importFn the function to import the decoder
* @param {function(import("../imagefiledirectory.js").ImageFileDirectory):Promise<BaseDecoderParameters>} decoderParameterFn
* @param {boolean} preferWorker_ Whether to prefer running the decoder in a worker
*/
export function addDecoder(cases: (number | undefined | (number | undefined)[]), importFn: () => Promise<typeof BaseDecoder>, decoderParameterFn?: (arg0: import("../imagefiledirectory.js").ImageFileDirectory) => Promise<BaseDecoderParameters>, preferWorker_?: boolean): void;
/**
* Get the required decoder parameters for a specific compression method
* @param {number|undefined} compression
* @param {import('../imagefiledirectory.js').ImageFileDirectory} fileDirectory
*/
export function getDecoderParameters(compression: number | undefined, fileDirectory: import("../imagefiledirectory.js").ImageFileDirectory): Promise<BaseDecoderParameters>;
/**
* Get a decoder for a specific compression and parameters
* @param {number} compression the compression method identifier
* @param {BaseDecoderParameters} decoderParameters the parameters for the decoder
* @returns {Promise<import('./basedecoder.js').default>}
*/
export function getDecoder(compression: number, decoderParameters: BaseDecoderParameters): Promise<import("./basedecoder.js").default>;
/**
* Whether to prefer running the decoder in a worker
* @param {number|undefined} compression the compression method identifier
* @returns {boolean}
*/
export function preferWorker(compression: number | undefined): boolean;
export type RegistryEntry = {
importFn: () => Promise<typeof BaseDecoder>;
decoderParameterFn: (arg0: import("../imagefiledirectory.js").ImageFileDirectory) => Promise<BaseDecoderParameters>;
preferWorker: boolean;
};
import type BaseDecoder from "./basedecoder.js";
import type { BaseDecoderParameters } from "./basedecoder.js";
//# sourceMappingURL=index.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/compression/index.js"],"names":[],"mappings":"AAmCA;;;;;;GAMG;AACH,kCALW,CAAC,MAAM,GAAC,SAAS,GAAC,CAAC,MAAM,GAAC,SAAS,CAAC,EAAE,CAAC,YACvC,MAAW,OAAO,CAAC,kBAAkB,CAAC,uBACtC,CAAS,IAAqD,EAArD,OAAO,0BAA0B,EAAE,kBAAkB,KAAE,OAAO,CAAC,qBAAqB,CAAC,kBAC9F,OAAO,QASjB;AAED;;;;GAIG;AACH,kDAHW,MAAM,GAAC,SAAS,iBAChB,OAAO,0BAA0B,EAAE,kBAAkB,kCAQ/D;AAED;;;;;GAKG;AACH,wCAJW,MAAM,qBACN,qBAAqB,GACnB,OAAO,CAAC,OAAO,kBAAkB,EAAE,OAAO,CAAC,CASvD;AAED;;;;GAIG;AACH,0CAHW,MAAM,GAAC,SAAS,GACd,OAAO,CAOnB;;cArFa,MAAW,OAAO,CAAC,kBAAkB,CAAC;wBACtC,CAAS,IAAqD,EAArD,OAAO,0BAA0B,EAAE,kBAAkB,KAAE,OAAO,CAAC,qBAAqB,CAAC;kBAC9F,OAAO;;6BANiC,kBAAkB;2CAAlB,kBAAkB"}
-175
View File
@@ -1,175 +0,0 @@
/** @import BaseDecoder, {BaseDecoderParameters} from "./basedecoder.js" */
/**
* @typedef {Object} RegistryEntry
* @property {function():Promise<typeof BaseDecoder>} importFn
* @property {function(import("../imagefiledirectory.js").ImageFileDirectory):Promise<BaseDecoderParameters>} decoderParameterFn
* @property {boolean} preferWorker
*/
/** @type {Map<number | undefined, RegistryEntry>} */
const registry = new Map();
/**
* Default decoder parameter retrieval function
* @param {import("../imagefiledirectory.js").ImageFileDirectory} fileDirectory
* @returns {Promise<BaseDecoderParameters>}
*/
async function defaultDecoderParameterFn(fileDirectory) {
const isTiled = !fileDirectory.hasTag('StripOffsets');
return /** @type {BaseDecoderParameters} */ ({
tileWidth: isTiled
? await fileDirectory.loadValue('TileWidth')
: await fileDirectory.loadValue('ImageWidth'),
tileHeight: isTiled
? await fileDirectory.loadValue('TileLength')
: (await fileDirectory.loadValue('RowsPerStrip')
|| await fileDirectory.loadValue('ImageLength')),
planarConfiguration: await fileDirectory.loadValue('PlanarConfiguration'),
bitsPerSample: await fileDirectory.loadValue('BitsPerSample'),
predictor: await fileDirectory.loadValue('Predictor') || 1,
});
}
/**
* Register a decoder for a specific compression method or a range of compressions
* @param {(number|undefined|(number|undefined)[])} cases ids of the compression methods to register for
* @param {function():Promise<typeof BaseDecoder>} importFn the function to import the decoder
* @param {function(import("../imagefiledirectory.js").ImageFileDirectory):Promise<BaseDecoderParameters>} decoderParameterFn
* @param {boolean} preferWorker_ Whether to prefer running the decoder in a worker
*/
export function addDecoder(cases, importFn, decoderParameterFn = defaultDecoderParameterFn, preferWorker_ = true) {
if (!Array.isArray(cases)) {
cases = [cases]; // eslint-disable-line no-param-reassign
}
cases.forEach((c) => {
registry.set(c, { importFn, decoderParameterFn, preferWorker: preferWorker_ });
});
}
/**
* Get the required decoder parameters for a specific compression method
* @param {number|undefined} compression
* @param {import('../imagefiledirectory.js').ImageFileDirectory} fileDirectory
*/
export async function getDecoderParameters(compression, fileDirectory) {
if (!registry.has(compression)) {
throw new Error(`Unknown compression method identifier: ${compression}`);
}
const { decoderParameterFn } = /** @type {RegistryEntry} */ (registry.get(compression));
return decoderParameterFn(fileDirectory);
}
/**
* Get a decoder for a specific compression and parameters
* @param {number} compression the compression method identifier
* @param {BaseDecoderParameters} decoderParameters the parameters for the decoder
* @returns {Promise<import('./basedecoder.js').default>}
*/
export async function getDecoder(compression, decoderParameters) {
if (!registry.has(compression)) {
throw new Error(`Unknown compression method identifier: ${compression}`);
}
const { importFn } = /** @type {RegistryEntry} */ (registry.get(compression));
const Decoder = await importFn();
return new Decoder(decoderParameters);
}
/**
* Whether to prefer running the decoder in a worker
* @param {number|undefined} compression the compression method identifier
* @returns {boolean}
*/
export function preferWorker(compression) {
if (!registry.has(compression)) {
throw new Error(`Unknown compression method identifier: ${compression}`);
}
return /** @type {RegistryEntry} */ (registry.get(compression)).preferWorker;
}
const defaultDecoderDefinitions = [
// No compression
{
cases: [undefined, 1],
importFn: () => import('./raw.js').then((m) => m.default),
preferWorker: false,
},
// LZW
{
cases: 5,
importFn: () => import('./lzw.js').then((m) => m.default),
},
// Old-style JPEG
{
cases: 6,
importFn: () => {
throw new Error('old style JPEG compression is not supported.');
},
},
// JPEG
{
cases: 7,
importFn: () => import('./jpeg.js').then((m) => m.default),
/**
* @param {import("../imagefiledirectory.js").ImageFileDirectory} fileDirectory
*/
decoderParameterFn: async (fileDirectory) => {
return {
...await defaultDecoderParameterFn(fileDirectory),
JPEGTables: await fileDirectory.loadValue('JPEGTables'),
};
},
},
// Deflate / Adobe Deflate
{
cases: [8, 32946],
importFn: () => import('./deflate.js').then((m) => m.default),
},
// PackBits
{
cases: 32773,
importFn: () => import('./packbits.js').then((m) => m.default),
},
// LERC
{
cases: 34887,
importFn: () => import('./lerc.js')
.then(async (m) => {
await m.zstd.init();
return m;
})
.then((m) => m.default),
/**
* @param {import("../imagefiledirectory.js").ImageFileDirectory} fileDirectory
*/
decoderParameterFn: async (fileDirectory) => {
return {
...await defaultDecoderParameterFn(fileDirectory),
LercParameters: await fileDirectory.loadValue('LercParameters'),
};
},
},
// zstd
{
cases: 50000,
importFn: () => import('./zstd.js')
.then(async (m) => {
await m.zstd.init();
return m;
})
.then((m) => m.default),
},
// WebP Images
{
cases: 50001,
importFn: () => import('./webimage.js').then((m) => m.default),
/**
* @param {import("../imagefiledirectory.js").ImageFileDirectory} fileDirectory
*/
decoderParameterFn: async (fileDirectory) => {
return {
...await defaultDecoderParameterFn(fileDirectory),
samplesPerPixel: Number(await fileDirectory.loadValue('SamplesPerPixel')) || 4,
};
},
preferWorker: false,
},
];
// Add default decoders to registry (end-user may override with other implementations)
for (const decoderDefinition of defaultDecoderDefinitions) {
const { cases, importFn, decoderParameterFn, preferWorker: preferWorker_ } = decoderDefinition;
addDecoder(cases, importFn, decoderParameterFn, preferWorker_);
}
//# sourceMappingURL=index.js.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/compression/index.js"],"names":[],"mappings":"AAAA,2EAA2E;AAE3E;;;;;GAKG;AAEH,qDAAqD;AACrD,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAE,CAAC;AAE3B;;;;GAIG;AACH,KAAK,UAAU,yBAAyB,CAAC,aAAa;IACpD,MAAM,OAAO,GAAG,CAAC,aAAa,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC;IACtD,OAAO,oCAAoC,CAAC,CAAC;QAC3C,SAAS,EAAE,OAAO;YAChB,CAAC,CAAC,MAAM,aAAa,CAAC,SAAS,CAAC,WAAW,CAAC;YAC5C,CAAC,CAAC,MAAM,aAAa,CAAC,SAAS,CAAC,YAAY,CAAC;QAC/C,UAAU,EAAE,OAAO;YACjB,CAAC,CAAC,MAAM,aAAa,CAAC,SAAS,CAAC,YAAY,CAAC;YAC7C,CAAC,CAAC,CACA,MAAM,aAAa,CAAC,SAAS,CAAC,cAAc,CAAC;mBAC1C,MAAM,aAAa,CAAC,SAAS,CAAC,aAAa,CAAC,CAChD;QACH,mBAAmB,EAAE,MAAM,aAAa,CAAC,SAAS,CAAC,qBAAqB,CAAC;QACzE,aAAa,EAAE,MAAM,aAAa,CAAC,SAAS,CAAC,eAAe,CAAC;QAC7D,SAAS,EAAE,MAAM,aAAa,CAAC,SAAS,CAAC,WAAW,CAAC,IAAI,CAAC;KAC3D,CAAC,CAAC;AACL,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,UAAU,CAAC,KAAK,EAAE,QAAQ,EAAE,kBAAkB,GAAG,yBAAyB,EAAE,aAAa,GAAG,IAAI;IAC9G,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QAC1B,KAAK,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,wCAAwC;IAC3D,CAAC;IACD,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE;QAClB,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,QAAQ,EAAE,kBAAkB,EAAE,YAAY,EAAE,aAAa,EAAE,CAAC,CAAC;IACjF,CAAC,CAAC,CAAC;AACL,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,oBAAoB,CAAC,WAAW,EAAE,aAAa;IACnE,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;QAC/B,MAAM,IAAI,KAAK,CAAC,0CAA0C,WAAW,EAAE,CAAC,CAAC;IAC3E,CAAC;IACD,MAAM,EAAE,kBAAkB,EAAE,GAAG,4BAA4B,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC;IACxF,OAAO,kBAAkB,CAAC,aAAa,CAAC,CAAC;AAC3C,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,UAAU,CAAC,WAAW,EAAE,iBAAiB;IAC7D,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;QAC/B,MAAM,IAAI,KAAK,CAAC,0CAA0C,WAAW,EAAE,CAAC,CAAC;IAC3E,CAAC;IACD,MAAM,EAAE,QAAQ,EAAE,GAAG,4BAA4B,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC;IAC9E,MAAM,OAAO,GAAG,MAAM,QAAQ,EAAE,CAAC;IACjC,OAAO,IAAI,OAAO,CAAC,iBAAiB,CAAC,CAAC;AACxC,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,YAAY,CAAC,WAAW;IACtC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;QAC/B,MAAM,IAAI,KAAK,CAAC,0CAA0C,WAAW,EAAE,CAAC,CAAC;IAC3E,CAAC;IACD,OAAO,4BAA4B,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,YAAY,CAAC;AAC/E,CAAC;AAED,MAAM,yBAAyB,GAAG;IAChC,iBAAiB;IACjB;QACE,KAAK,EAAE,CAAC,SAAS,EAAE,CAAC,CAAC;QACrB,QAAQ,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC;QACzD,YAAY,EAAE,KAAK;KACpB;IACD,MAAM;IACN;QACE,KAAK,EAAE,CAAC;QACR,QAAQ,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC;KAC1D;IACD,iBAAiB;IACjB;QACE,KAAK,EAAE,CAAC;QACR,QAAQ,EAAE,GAAG,EAAE;YACb,MAAM,IAAI,KAAK,CAAC,8CAA8C,CAAC,CAAC;QAClE,CAAC;KACF;IACD,OAAO;IACP;QACE,KAAK,EAAE,CAAC;QACR,QAAQ,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC;QAC1D;;WAEG;QACH,kBAAkB,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE;YAC1C,OAAO;gBACL,GAAG,MAAM,yBAAyB,CAAC,aAAa,CAAC;gBACjD,UAAU,EAAE,MAAM,aAAa,CAAC,SAAS,CAAC,YAAY,CAAC;aACxD,CAAC;QACJ,CAAC;KACF;IACD,0BAA0B;IAC1B;QACE,KAAK,EAAE,CAAC,CAAC,EAAE,KAAK,CAAC;QACjB,QAAQ,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC;KAC9D;IACD,WAAW;IACX;QACE,KAAK,EAAE,KAAK;QACZ,QAAQ,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,eAAe,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC;KAC/D;IACD,OAAO;IACP;QACE,KAAK,EAAE,KAAK;QACZ,QAAQ,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,WAAW,CAAC;aAChC,IAAI,CAAC,KAAK,EAAE,CAAC,EAAE,EAAE;YAChB,MAAM,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;YACpB,OAAO,CAAC,CAAC;QACX,CAAC,CAAC;aACD,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC;QACzB;;WAEG;QACH,kBAAkB,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE;YAC1C,OAAO;gBACL,GAAG,MAAM,yBAAyB,CAAC,aAAa,CAAC;gBACjD,cAAc,EAAE,MAAM,aAAa,CAAC,SAAS,CAAC,gBAAgB,CAAC;aAChE,CAAC;QACJ,CAAC;KACF;IACD,OAAO;IACP;QACE,KAAK,EAAE,KAAK;QACZ,QAAQ,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,WAAW,CAAC;aAChC,IAAI,CAAC,KAAK,EAAE,CAAC,EAAE,EAAE;YAChB,MAAM,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;YACpB,OAAO,CAAC,CAAC;QACX,CAAC,CAAC;aACD,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC;KAC1B;IACD,cAAc;IACd;QACE,KAAK,EAAE,KAAK;QACZ,QAAQ,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,eAAe,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC;QAC9D;;WAEG;QACH,kBAAkB,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE;YAC1C,OAAO;gBACL,GAAG,MAAM,yBAAyB,CAAC,aAAa,CAAC;gBACjD,eAAe,EAAE,MAAM,CAAC,MAAM,aAAa,CAAC,SAAS,CAAC,iBAAiB,CAAC,CAAC,IAAI,CAAC;aAC/E,CAAC;QACJ,CAAC;QACD,YAAY,EAAE,KAAK;KACpB;CACF,CAAC;AAEF,sFAAsF;AACtF,KAAK,MAAM,iBAAiB,IAAI,yBAAyB,EAAE,CAAC;IAC1D,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,kBAAkB,EAAE,YAAY,EAAE,aAAa,EAAE,GAAG,iBAAiB,CAAC;IAC/F,UAAU,CAAC,KAAK,EAAE,QAAQ,EAAE,kBAAkB,EAAE,aAAa,CAAC,CAAC;AACjE,CAAC"}
-80
View File
@@ -1,80 +0,0 @@
export default class JpegDecoder extends BaseDecoder {
/**
* @param {import('./basedecoder.js').BaseDecoderParameters & { JPEGTables?: Uint8Array }} parameters
*/
constructor(parameters: import("./basedecoder.js").BaseDecoderParameters & {
JPEGTables?: Uint8Array;
});
reader: JpegStreamReader;
/** @param {ArrayBuffer} buffer */
decodeBlock(buffer: ArrayBuffer): ArrayBuffer;
}
export type HuffmanNode = (number | HuffmanNode)[];
export type Code = {
children: HuffmanNode;
index: number;
};
export type JpegComponent = {
h: number;
v: number;
quantizationIdx?: number | undefined;
quantizationTable?: Int32Array<ArrayBufferLike> | undefined;
blocksPerLine: number;
blocksPerColumn: number;
blocks: Int32Array[][];
huffmanTableDC?: HuffmanNode | undefined;
huffmanTableAC?: HuffmanNode | undefined;
pred?: number | undefined;
};
export type JpegFrame = {
extended: boolean;
progressive: boolean;
precision: number;
scanLines: number;
samplesPerLine: number;
components: {
[x: string]: JpegComponent;
};
componentsOrder: number[];
maxH: number;
maxV: number;
mcusPerLine: number;
mcusPerColumn: number;
};
import BaseDecoder from './basedecoder.js';
declare class JpegStreamReader {
jfif: {
version: {
major: number;
minor: number;
};
densityUnits: number;
xDensity: number;
yDensity: number;
thumbWidth: number;
thumbHeight: number;
thumbData: Uint8Array<ArrayBufferLike>;
} | null;
adobe: {
version: number;
flags0: number;
flags1: number;
transformCode: number;
} | null;
/** @type {number} */
resetInterval: number;
/** @type {Int32Array[]} */
quantizationTables: Int32Array[];
/** @type {HuffmanNode[]} */
huffmanTablesAC: HuffmanNode[];
/** @type {HuffmanNode[]} */
huffmanTablesDC: HuffmanNode[];
/** @type {JpegFrame[]} */
frames: JpegFrame[];
resetFrames(): void;
/** @param {Uint8Array} data */
parse(data: Uint8Array): void;
getResult(): Uint8Array<ArrayBuffer>;
}
export {};
//# sourceMappingURL=jpeg.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"jpeg.d.ts","sourceRoot":"","sources":["../../src/compression/jpeg.js"],"names":[],"mappings":"AAykCA;IACE;;OAEG;IACH,wBAFW,OAAO,kBAAkB,EAAE,qBAAqB,GAAG;QAAE,UAAU,CAAC,EAAE,UAAU,CAAA;KAAE,EAQxF;IAJC,yBAAoC;IAMtC,kCAAkC;IAClC,oBADY,WAAW,eAKtB;CACF;0BAviCa,CAAC,MAAM,GAAC,WAAW,CAAC,EAAE;mBACtB;IAAC,QAAQ,EAAE,WAAW,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAC;;OAItC,MAAM;OACN,MAAM;;;mBAGN,MAAM;qBACN,MAAM;YACN,UAAU,EAAE,EAAE;;;;;;cAQd,OAAO;iBACP,OAAO;eACP,MAAM;eACN,MAAM;oBACN,MAAM;;;;qBAEN,MAAM,EAAE;UACR,MAAM;UACN,MAAM;iBACN,MAAM;mBACN,MAAM;;wBAjFI,kBAAkB;AAsvB1C;IAEI;;;;;;;;;;;aAAgB;IAChB;;;;;aAAiB;IAEjB,qBAAqB;IACrB,eADW,MAAM,CACK;IAEtB,2BAA2B;IAC3B,oBADW,UAAU,EAAE,CACK;IAC5B,4BAA4B;IAC5B,iBADW,WAAW,EAAE,CACC;IACzB,4BAA4B;IAC5B,iBADW,WAAW,EAAE,CACC;IACzB,0BAA0B;IAC1B,QADW,SAAS,EAAE,CACN;IAGlB,oBAEC;IAED,+BAA+B;IAC/B,YADY,UAAU,QAsQrB;IAED,qCAkDC;CACF"}
File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More