commit 4fa600a3a3bf0f96b85037535bd2a77f651f651d Author: ReaperOfVeriod Date: Fri Aug 14 11:44:00 2026 +0200 first commit diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..e69de29 diff --git a/Headshot.png b/Headshot.png new file mode 100644 index 0000000..cfb38af Binary files /dev/null and b/Headshot.png differ diff --git a/README.md b/README.md new file mode 100644 index 0000000..e69de29 diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..e69de29 diff --git a/dummy.pdf b/dummy.pdf new file mode 100644 index 0000000..774c2ea Binary files /dev/null and b/dummy.pdf differ diff --git a/encoded.png b/encoded.png new file mode 100644 index 0000000..c5b7138 Binary files /dev/null and b/encoded.png differ diff --git a/extracted.pdf b/extracted.pdf new file mode 100644 index 0000000..774c2ea Binary files /dev/null and b/extracted.pdf differ diff --git a/node_modules/.bin/semver b/node_modules/.bin/semver new file mode 120000 index 0000000..5aaadf4 --- /dev/null +++ b/node_modules/.bin/semver @@ -0,0 +1 @@ +../semver/bin/semver.js \ No newline at end of file diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 0000000..ea78177 --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,1311 @@ +{ + "name": "stegonography-app", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@emnapi/runtime": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", + "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@img/colour": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", + "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.2.tgz", + "integrity": "sha512-ITPEtgffGJ0S6G9dRyw/366tJQqFRcHWPHhC+Stpg3Z8AEMrDrTr2lhdz4f/Y/HMbRh//7Z5mBzEpVdi62Oc3w==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.2.tgz", + "integrity": "sha512-m0lrLiUt+lBYnCFr8qV/65yMR4E/c7/wf78I5eKTdkEakFAlZ9QlzEM3QIhhAwVeUhLAHLcCq7a7Vszq/oFNZQ==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.35.3", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.3.tgz", + "integrity": "sha512-8pqvxubL2PGdhlPy6GLqzDYMUjyRmKAwKHYKixpdJYBUK7PJ0C029XdsnpFIdgRZG68fZiGdHVWcKPvtiPB4cA==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.3.2" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.35.3", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.3.tgz", + "integrity": "sha512-6O1NPKcDVj9QEdg7Hx549EX8U0rp6yXQERqru6yRN7fGBn32UvIRJUlWnk+8xDCiG76hXVBbX82NZ/ZKr0euIg==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.3.2" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.35.3", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.3.tgz", + "integrity": "sha512-cZ0XkcYGpHZkqW6iCkqTcmUC0CD9DhD5d/qeZlZkfRBn6GnHniZXLUo5+9xw8Iv76YE6LQFN9YNBlKREcCG76w==", + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.11.1" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/append-field": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz", + "integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==", + "license": "MIT" + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/body-parser": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz", + "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^2.0.0", + "debug": "^4.4.3", + "http-errors": "^2.0.1", + "iconv-lite": "^0.7.2", + "on-finished": "^2.4.1", + "qs": "^6.15.2", + "raw-body": "^3.0.2", + "type-is": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/body-parser/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "license": "MIT" + }, + "node_modules/busboy": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz", + "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==", + "dependencies": { + "streamsearch": "^1.1.0" + }, + "engines": { + "node": ">=10.16.0" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dev": true, + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/concat-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz", + "integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==", + "engines": [ + "node >= 6.0" + ], + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.0.2", + "typedarray": "^0.0.6" + } + }, + "node_modules/content-disposition": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz", + "integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "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==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz", + "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.1", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.7", + "qs": "^6.14.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/form-data": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", + "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.4", + "mime-types": "^2.1.35" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/form-data/node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/form-data/node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "license": "MIT" + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.1.tgz", + "integrity": "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/multer": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/multer/-/multer-2.2.0.tgz", + "integrity": "sha512-6rdyFg2kLrMh9Jee7/BMPuV9lEAd7lLW2YUpF9/YxR7njyoUwwQ0ZPh3TaIY50Sw6vlyD2HW3wGOkTS4P79xrQ==", + "license": "MIT", + "dependencies": { + "append-field": "^1.0.0", + "busboy": "^1.6.0", + "concat-stream": "^2.0.0", + "type-is": "^1.6.18" + }, + "engines": { + "node": ">= 10.16.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/multer/node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/multer/node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/multer/node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/multer/node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/negotiator": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", + "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "8.4.2", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", + "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/qs": { + "version": "6.15.3", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.3.tgz", + "integrity": "sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==", + "license": "BSD-3-Clause", + "dependencies": { + "es-define-property": "^1.0.1", + "side-channel": "^1.1.1" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz", + "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.1", + "mime-types": "^3.0.2", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/serve-static": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/sharp": { + "version": "0.35.3", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.3.tgz", + "integrity": "sha512-ej0zVHuZGHCiABXcNxeYhpRnPNPAcvbG8RMdBAhDAxLKkCRVSpK3Iyu7qbqw3JMzoj0REeM6f3tJLtVwl0023Q==", + "license": "Apache-2.0", + "dependencies": { + "@img/colour": "^1.1.0", + "detect-libc": "^2.1.2", + "semver": "^7.8.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.35.3", + "@img/sharp-darwin-x64": "0.35.3", + "@img/sharp-freebsd-wasm32": "0.35.3", + "@img/sharp-libvips-darwin-arm64": "1.3.2", + "@img/sharp-libvips-darwin-x64": "1.3.2", + "@img/sharp-libvips-linux-arm": "1.3.2", + "@img/sharp-libvips-linux-arm64": "1.3.2", + "@img/sharp-libvips-linux-ppc64": "1.3.2", + "@img/sharp-libvips-linux-riscv64": "1.3.2", + "@img/sharp-libvips-linux-s390x": "1.3.2", + "@img/sharp-libvips-linux-x64": "1.3.2", + "@img/sharp-libvips-linuxmusl-arm64": "1.3.2", + "@img/sharp-libvips-linuxmusl-x64": "1.3.2", + "@img/sharp-linux-arm": "0.35.3", + "@img/sharp-linux-arm64": "0.35.3", + "@img/sharp-linux-ppc64": "0.35.3", + "@img/sharp-linux-riscv64": "0.35.3", + "@img/sharp-linux-s390x": "0.35.3", + "@img/sharp-linux-x64": "0.35.3", + "@img/sharp-linuxmusl-arm64": "0.35.3", + "@img/sharp-linuxmusl-x64": "0.35.3", + "@img/sharp-webcontainers-wasm32": "0.35.3", + "@img/sharp-win32-arm64": "0.35.3", + "@img/sharp-win32-ia32": "0.35.3", + "@img/sharp-win32-x64": "0.35.3" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/side-channel": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/streamsearch": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz", + "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD", + "optional": true + }, + "node_modules/type-is": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz", + "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==", + "license": "MIT", + "dependencies": { + "content-type": "^2.0.0", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/type-is/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/typedarray": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", + "integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==", + "license": "MIT" + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + } + } +} diff --git a/node_modules/@emnapi/runtime/LICENSE b/node_modules/@emnapi/runtime/LICENSE new file mode 100644 index 0000000..05a5944 --- /dev/null +++ b/node_modules/@emnapi/runtime/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-present Toyobayashi + +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. diff --git a/node_modules/@emnapi/runtime/README.md b/node_modules/@emnapi/runtime/README.md new file mode 100644 index 0000000..c98dddc --- /dev/null +++ b/node_modules/@emnapi/runtime/README.md @@ -0,0 +1 @@ +See [https://github.com/toyobayashi/emnapi](https://github.com/toyobayashi/emnapi) diff --git a/node_modules/@emnapi/runtime/dist/emnapi.cjs.js b/node_modules/@emnapi/runtime/dist/emnapi.cjs.js new file mode 100644 index 0000000..5bba2ba --- /dev/null +++ b/node_modules/@emnapi/runtime/dist/emnapi.cjs.js @@ -0,0 +1,1398 @@ +const externalValue = new WeakMap(); +function isExternal(object) { + return externalValue.has(object); +} +const External = (() => { + function External(value) { + Object.setPrototypeOf(this, null); + externalValue.set(this, value); + } + External.prototype = null; + return External; +})(); +function getExternalValue(external) { + if (!isExternal(external)) { + throw new TypeError('not external'); + } + return externalValue.get(external); +} + +const supportNewFunction = (function () { + let f; + try { + f = new Function(); + } + catch (_) { + return false; + } + return typeof f === 'function'; +})(); +const _global = (function () { + if (typeof globalThis !== 'undefined') + return globalThis; + let g = (function () { return this; })(); + if (!g && supportNewFunction) { + try { + g = new Function('return this')(); + } + catch (_) { } + } + if (!g) { + if (typeof __webpack_public_path__ === 'undefined') { + if (typeof global !== 'undefined') + return global; + } + if (typeof window !== 'undefined') + return window; + if (typeof self !== 'undefined') + return self; + } + return g; +})(); +class TryCatch { + constructor() { + this._exception = undefined; + this._caught = false; + } + isEmpty() { + return !this._caught; + } + hasCaught() { + return this._caught; + } + exception() { + return this._exception; + } + setError(err) { + this._caught = true; + this._exception = err; + } + reset() { + this._caught = false; + this._exception = undefined; + } + extractException() { + const e = this._exception; + this.reset(); + return e; + } +} +const canSetFunctionName = (function () { + var _a; + try { + return Boolean((_a = Object.getOwnPropertyDescriptor(Function.prototype, 'name')) === null || _a === void 0 ? void 0 : _a.configurable); + } + catch (_) { + return false; + } +})(); +const supportReflect = typeof Reflect === 'object'; +const supportFinalizer = (typeof FinalizationRegistry !== 'undefined') && (typeof WeakRef !== 'undefined'); +const supportWeakSymbol = (function () { + try { + const sym = Symbol(); + new WeakRef(sym); + new WeakMap().set(sym, undefined); + } + catch (_) { + return false; + } + return true; +})(); +const supportBigInt = typeof BigInt !== 'undefined'; +function isReferenceType(v) { + return (typeof v === 'object' && v !== null) || typeof v === 'function'; +} +const _require = (function () { + let nativeRequire; + if (typeof __webpack_public_path__ !== 'undefined') { + nativeRequire = (function () { + return typeof __non_webpack_require__ !== 'undefined' ? __non_webpack_require__ : undefined; + })(); + } + else { + nativeRequire = (function () { + return typeof __webpack_public_path__ !== 'undefined' ? (typeof __non_webpack_require__ !== 'undefined' ? __non_webpack_require__ : undefined) : (typeof require !== 'undefined' ? require : undefined); + })(); + } + return nativeRequire; +})(); +const _MessageChannel = typeof MessageChannel === 'function' + ? MessageChannel + : (function () { + try { + return _require('worker_threads').MessageChannel; + } + catch (_) { } + return undefined; + })(); +const _setImmediate = typeof setImmediate === 'function' + ? setImmediate.bind(_global) + : function (callback) { + if (typeof callback !== 'function') { + throw new TypeError('The "callback" argument must be of type function'); + } + if (_MessageChannel) { + let channel = new _MessageChannel(); + channel.port1.onmessage = function () { + channel.port1.onmessage = null; + channel = undefined; + callback(); + }; + channel.port2.postMessage(null); + } + else { + setTimeout(callback, 0); + } + }; +const _Buffer = typeof Buffer === 'function' + ? Buffer + : (function () { + try { + return _require('buffer').Buffer; + } + catch (_) { } + return undefined; + })(); +const version = "1.11.3"; +const NODE_API_SUPPORTED_VERSION_MIN = 1; +const NODE_API_SUPPORTED_VERSION_MAX = 10; +const NAPI_VERSION_EXPERIMENTAL = 2147483647; +const NODE_API_DEFAULT_MODULE_API_VERSION = 8; + +class Handle { + constructor(id, value) { + this.id = id; + this.value = value; + } + data() { + return getExternalValue(this.value); + } + isNumber() { + return typeof this.value === 'number'; + } + isBigInt() { + return typeof this.value === 'bigint'; + } + isString() { + return typeof this.value === 'string'; + } + isFunction() { + return typeof this.value === 'function'; + } + isExternal() { + return isExternal(this.value); + } + isObject() { + return typeof this.value === 'object' && this.value !== null; + } + isArray() { + return Array.isArray(this.value); + } + isArrayBuffer() { + return (this.value instanceof ArrayBuffer); + } + isTypedArray() { + return (ArrayBuffer.isView(this.value)) && !(this.value instanceof DataView); + } + isBuffer(BufferConstructor) { + if (ArrayBuffer.isView(this.value)) + return true; + BufferConstructor !== null && BufferConstructor !== void 0 ? BufferConstructor : (BufferConstructor = _Buffer); + return typeof BufferConstructor === 'function' && BufferConstructor.isBuffer(this.value); + } + isDataView() { + return (this.value instanceof DataView); + } + isDate() { + return (this.value instanceof Date); + } + isPromise() { + return (this.value instanceof Promise); + } + isBoolean() { + return typeof this.value === 'boolean'; + } + isUndefined() { + return this.value === undefined; + } + isSymbol() { + return typeof this.value === 'symbol'; + } + isNull() { + return this.value === null; + } + dispose() { + this.value = undefined; + } +} +class ConstHandle extends Handle { + constructor(id, value) { + super(id, value); + } + dispose() { } +} +class HandleStore { + constructor() { + this._values = [ + undefined, + HandleStore.UNDEFINED, + HandleStore.NULL, + HandleStore.FALSE, + HandleStore.TRUE, + HandleStore.GLOBAL + ]; + this._next = HandleStore.MIN_ID; + } + push(value) { + let h; + const next = this._next; + const values = this._values; + if (next < values.length) { + h = values[next]; + h.value = value; + } + else { + h = new Handle(next, value); + values[next] = h; + } + this._next++; + return h; + } + erase(start, end) { + this._next = start; + const values = this._values; + for (let i = start; i < end; ++i) { + values[i].dispose(); + } + } + get(id) { + return this._values[id]; + } + swap(a, b) { + const values = this._values; + const h = values[a]; + values[a] = values[b]; + values[a].id = Number(a); + values[b] = h; + h.id = Number(b); + } + dispose() { + this._values.length = HandleStore.MIN_ID; + this._next = HandleStore.MIN_ID; + } +} +HandleStore.UNDEFINED = new ConstHandle(1, undefined); +HandleStore.NULL = new ConstHandle(2, null); +HandleStore.FALSE = new ConstHandle(3, false); +HandleStore.TRUE = new ConstHandle(4, true); +HandleStore.GLOBAL = new ConstHandle(5, _global); +HandleStore.MIN_ID = 6; + +class HandleScope { + constructor(handleStore, id, parentScope, start, end = start) { + this.handleStore = handleStore; + this.id = id; + this.parent = parentScope; + this.child = null; + if (parentScope !== null) + parentScope.child = this; + this.start = start; + this.end = end; + this._escapeCalled = false; + this.callbackInfo = { + thiz: undefined, + data: 0, + args: undefined, + fn: undefined + }; + } + add(value) { + const h = this.handleStore.push(value); + this.end++; + return h; + } + addExternal(data) { + return this.add(new External(data)); + } + dispose() { + if (this._escapeCalled) + this._escapeCalled = false; + if (this.start === this.end) + return; + this.handleStore.erase(this.start, this.end); + } + escape(handle) { + if (this._escapeCalled) + return null; + this._escapeCalled = true; + if (handle < this.start || handle >= this.end) { + return null; + } + this.handleStore.swap(handle, this.start); + const h = this.handleStore.get(this.start); + this.start++; + this.parent.end++; + return h; + } + escapeCalled() { + return this._escapeCalled; + } +} + +class ScopeStore { + constructor() { + this._rootScope = new HandleScope(null, 0, null, 1, HandleStore.MIN_ID); + this.currentScope = this._rootScope; + this._values = [undefined]; + } + get(id) { + return this._values[id]; + } + openScope(handleStore) { + const currentScope = this.currentScope; + let scope = currentScope.child; + if (scope !== null) { + scope.start = scope.end = currentScope.end; + } + else { + const id = currentScope.id + 1; + scope = new HandleScope(handleStore, id, currentScope, currentScope.end); + this._values[id] = scope; + } + this.currentScope = scope; + return scope; + } + closeScope() { + const scope = this.currentScope; + this.currentScope = scope.parent; + scope.dispose(); + } + dispose() { + this.currentScope = this._rootScope; + this._values.length = 1; + } +} + +class RefTracker { + constructor() { + this._next = null; + this._prev = null; + } + dispose() { } + finalize() { } + link(list) { + this._prev = list; + this._next = list._next; + if (this._next !== null) { + this._next._prev = this; + } + list._next = this; + } + unlink() { + if (this._prev !== null) { + this._prev._next = this._next; + } + if (this._next !== null) { + this._next._prev = this._prev; + } + this._prev = null; + this._next = null; + } + static finalizeAll(list) { + while (list._next !== null) { + list._next.finalize(); + } + } +} + +class Finalizer { + constructor(envObject, _finalizeCallback = 0, _finalizeData = 0, _finalizeHint = 0) { + this.envObject = envObject; + this._finalizeCallback = _finalizeCallback; + this._finalizeData = _finalizeData; + this._finalizeHint = _finalizeHint; + this._makeDynCall_vppp = envObject.makeDynCall_vppp; + } + callback() { return this._finalizeCallback; } + data() { return this._finalizeData; } + hint() { return this._finalizeHint; } + resetEnv() { + this.envObject = undefined; + } + resetFinalizer() { + this._finalizeCallback = 0; + this._finalizeData = 0; + this._finalizeHint = 0; + } + callFinalizer() { + const finalize_callback = this._finalizeCallback; + const finalize_data = this._finalizeData; + const finalize_hint = this._finalizeHint; + this.resetFinalizer(); + if (!finalize_callback) + return; + const fini = Number(finalize_callback); + if (!this.envObject) { + this._makeDynCall_vppp(fini)(0, finalize_data, finalize_hint); + } + else { + this.envObject.callFinalizer(fini, finalize_data, finalize_hint); + } + } + dispose() { + this.envObject = undefined; + this._makeDynCall_vppp = undefined; + } +} + +class TrackedFinalizer extends RefTracker { + static create(envObject, finalize_callback, finalize_data, finalize_hint) { + const finalizer = new TrackedFinalizer(envObject, finalize_callback, finalize_data, finalize_hint); + finalizer.link(envObject.finalizing_reflist); + return finalizer; + } + constructor(envObject, finalize_callback, finalize_data, finalize_hint) { + super(); + this._finalizer = new Finalizer(envObject, finalize_callback, finalize_data, finalize_hint); + } + data() { + return this._finalizer.data(); + } + dispose() { + if (!this._finalizer) + return; + this.unlink(); + this._finalizer.envObject.dequeueFinalizer(this); + this._finalizer.dispose(); + this._finalizer = undefined; + super.dispose(); + } + finalize() { + this.unlink(); + let error; + let caught = false; + try { + this._finalizer.callFinalizer(); + } + catch (err) { + caught = true; + error = err; + } + this.dispose(); + if (caught) { + throw error; + } + } +} + +function throwNodeApiVersionError(moduleName, moduleApiVersion) { + const errorMessage = `${moduleName} requires Node-API version ${moduleApiVersion}, but this version of Node.js only supports version ${NODE_API_SUPPORTED_VERSION_MAX} add-ons.`; + throw new Error(errorMessage); +} +function handleThrow(envObject, value) { + if (envObject.terminatedOrTerminating()) { + return; + } + throw value; +} +class Env { + constructor(ctx, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort) { + this.ctx = ctx; + this.moduleApiVersion = moduleApiVersion; + this.makeDynCall_vppp = makeDynCall_vppp; + this.makeDynCall_vp = makeDynCall_vp; + this.abort = abort; + this.openHandleScopes = 0; + this.instanceData = null; + this.tryCatch = new TryCatch(); + this.refs = 1; + this.reflist = new RefTracker(); + this.finalizing_reflist = new RefTracker(); + this.pendingFinalizers = []; + this.lastError = { + errorCode: 0, + engineErrorCode: 0, + engineReserved: 0 + }; + this.inGcFinalizer = false; + this._bindingMap = new WeakMap(); + this.id = 0; + } + canCallIntoJs() { + return true; + } + terminatedOrTerminating() { + return !this.canCallIntoJs(); + } + ref() { + this.refs++; + } + unref() { + this.refs--; + if (this.refs === 0) { + this.dispose(); + } + } + ensureHandle(value) { + return this.ctx.ensureHandle(value); + } + ensureHandleId(value) { + return this.ensureHandle(value).id; + } + clearLastError() { + const lastError = this.lastError; + if (lastError.errorCode !== 0) + lastError.errorCode = 0; + if (lastError.engineErrorCode !== 0) + lastError.engineErrorCode = 0; + if (lastError.engineReserved !== 0) + lastError.engineReserved = 0; + return 0; + } + setLastError(error_code, engine_error_code = 0, engine_reserved = 0) { + const lastError = this.lastError; + if (lastError.errorCode !== error_code) + lastError.errorCode = error_code; + if (lastError.engineErrorCode !== engine_error_code) + lastError.engineErrorCode = engine_error_code; + if (lastError.engineReserved !== engine_reserved) + lastError.engineReserved = engine_reserved; + return error_code; + } + getReturnStatus() { + return !this.tryCatch.hasCaught() ? 0 : this.setLastError(10); + } + callIntoModule(fn, handleException = handleThrow) { + const openHandleScopesBefore = this.openHandleScopes; + this.clearLastError(); + const r = fn(this); + if (openHandleScopesBefore !== this.openHandleScopes) { + this.abort('open_handle_scopes != open_handle_scopes_before'); + } + if (this.tryCatch.hasCaught()) { + const err = this.tryCatch.extractException(); + handleException(this, err); + } + return r; + } + invokeFinalizerFromGC(finalizer) { + if (this.moduleApiVersion !== NAPI_VERSION_EXPERIMENTAL) { + this.enqueueFinalizer(finalizer); + } + else { + const saved = this.inGcFinalizer; + this.inGcFinalizer = true; + try { + finalizer.finalize(); + } + finally { + this.inGcFinalizer = saved; + } + } + } + checkGCAccess() { + if (this.moduleApiVersion === NAPI_VERSION_EXPERIMENTAL && this.inGcFinalizer) { + this.abort('Finalizer is calling a function that may affect GC state.\n' + + 'The finalizers are run directly from GC and must not affect GC ' + + 'state.\n' + + 'Use `node_api_post_finalizer` from inside of the finalizer to work ' + + 'around this issue.\n' + + 'It schedules the call as a new task in the event loop.'); + } + } + enqueueFinalizer(finalizer) { + if (this.pendingFinalizers.indexOf(finalizer) === -1) { + this.pendingFinalizers.push(finalizer); + } + } + dequeueFinalizer(finalizer) { + const index = this.pendingFinalizers.indexOf(finalizer); + if (index !== -1) { + this.pendingFinalizers.splice(index, 1); + } + } + deleteMe() { + RefTracker.finalizeAll(this.finalizing_reflist); + RefTracker.finalizeAll(this.reflist); + this.tryCatch.extractException(); + this.ctx.envStore.remove(this.id); + } + dispose() { + if (this.id === 0) + return; + this.deleteMe(); + this.finalizing_reflist.dispose(); + this.reflist.dispose(); + this.id = 0; + } + initObjectBinding(value) { + const binding = { + wrapped: 0, + tag: null + }; + this._bindingMap.set(value, binding); + return binding; + } + getObjectBinding(value) { + if (this._bindingMap.has(value)) { + return this._bindingMap.get(value); + } + return this.initObjectBinding(value); + } + setInstanceData(data, finalize_cb, finalize_hint) { + if (this.instanceData) { + this.instanceData.dispose(); + } + this.instanceData = TrackedFinalizer.create(this, finalize_cb, data, finalize_hint); + } + getInstanceData() { + return this.instanceData ? this.instanceData.data() : 0; + } +} +class NodeEnv extends Env { + constructor(ctx, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding) { + super(ctx, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort); + this.filename = filename; + this.nodeBinding = nodeBinding; + this.destructing = false; + this.finalizationScheduled = false; + } + deleteMe() { + this.destructing = true; + this.drainFinalizerQueue(); + super.deleteMe(); + } + canCallIntoJs() { + return super.canCallIntoJs() && this.ctx.canCallIntoJs(); + } + triggerFatalException(err) { + if (this.nodeBinding) { + this.nodeBinding.napi.fatalException(err); + } + else { + if (typeof process === 'object' && process !== null && typeof process._fatalException === 'function') { + const handled = process._fatalException(err); + if (!handled) { + console.error(err); + process.exit(1); + } + } + else { + throw err; + } + } + } + callbackIntoModule(enforceUncaughtExceptionPolicy, fn) { + return this.callIntoModule(fn, (envObject, err) => { + if (envObject.terminatedOrTerminating()) { + return; + } + const hasProcess = typeof process === 'object' && process !== null; + const hasForceFlag = hasProcess ? Boolean(process.execArgv && (process.execArgv.indexOf('--force-node-api-uncaught-exceptions-policy') !== -1)) : false; + if (envObject.moduleApiVersion < 10 && !hasForceFlag && !enforceUncaughtExceptionPolicy) { + const warn = hasProcess && typeof process.emitWarning === 'function' + ? process.emitWarning + : function (warning, type, code) { + if (warning instanceof Error) { + console.warn(warning.toString()); + } + else { + const prefix = code ? `[${code}] ` : ''; + console.warn(`${prefix}${type || 'Warning'}: ${warning}`); + } + }; + warn('Uncaught Node-API callback exception detected, please run node with option --force-node-api-uncaught-exceptions-policy=true to handle those exceptions properly.', 'DeprecationWarning', 'DEP0168'); + return; + } + envObject.triggerFatalException(err); + }); + } + callFinalizer(cb, data, hint) { + this.callFinalizerInternal(1, cb, data, hint); + } + callFinalizerInternal(forceUncaught, cb, data, hint) { + const f = this.makeDynCall_vppp(cb); + const env = this.id; + const scope = this.ctx.openScope(this); + try { + this.callbackIntoModule(Boolean(forceUncaught), () => { f(env, data, hint); }); + } + finally { + this.ctx.closeScope(this, scope); + } + } + enqueueFinalizer(finalizer) { + super.enqueueFinalizer(finalizer); + if (!this.finalizationScheduled && !this.destructing) { + this.finalizationScheduled = true; + this.ref(); + _setImmediate(() => { + this.finalizationScheduled = false; + this.unref(); + this.drainFinalizerQueue(); + }); + } + } + drainFinalizerQueue() { + while (this.pendingFinalizers.length > 0) { + const refTracker = this.pendingFinalizers.shift(); + refTracker.finalize(); + } + } +} +function newEnv(ctx, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding) { + moduleApiVersion = typeof moduleApiVersion !== 'number' ? NODE_API_DEFAULT_MODULE_API_VERSION : moduleApiVersion; + if (moduleApiVersion < NODE_API_DEFAULT_MODULE_API_VERSION) { + moduleApiVersion = NODE_API_DEFAULT_MODULE_API_VERSION; + } + else if (moduleApiVersion > NODE_API_SUPPORTED_VERSION_MAX && moduleApiVersion !== NAPI_VERSION_EXPERIMENTAL) { + throwNodeApiVersionError(filename, moduleApiVersion); + } + const env = new NodeEnv(ctx, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding); + ctx.envStore.add(env); + ctx.addCleanupHook(env, () => { env.unref(); }, 0); + return env; +} + +class EmnapiError extends Error { + constructor(message) { + super(message); + const ErrorConstructor = new.target; + const proto = ErrorConstructor.prototype; + if (!(this instanceof EmnapiError)) { + const setPrototypeOf = Object.setPrototypeOf; + if (typeof setPrototypeOf === 'function') { + setPrototypeOf.call(Object, this, proto); + } + else { + this.__proto__ = proto; + } + if (typeof Error.captureStackTrace === 'function') { + Error.captureStackTrace(this, ErrorConstructor); + } + } + } +} +Object.defineProperty(EmnapiError.prototype, 'name', { + configurable: true, + writable: true, + value: 'EmnapiError' +}); +class NotSupportWeakRefError extends EmnapiError { + constructor(api, message) { + super(`${api}: The current runtime does not support "FinalizationRegistry" and "WeakRef".${message ? ` ${message}` : ''}`); + } +} +Object.defineProperty(NotSupportWeakRefError.prototype, 'name', { + configurable: true, + writable: true, + value: 'NotSupportWeakRefError' +}); +class NotSupportBufferError extends EmnapiError { + constructor(api, message) { + super(`${api}: The current runtime does not support "Buffer". Consider using buffer polyfill to make sure \`globalThis.Buffer\` is defined.${message ? ` ${message}` : ''}`); + } +} +Object.defineProperty(NotSupportBufferError.prototype, 'name', { + configurable: true, + writable: true, + value: 'NotSupportBufferError' +}); + +class StrongRef { + constructor(value) { + this._value = value; + } + deref() { + return this._value; + } + dispose() { + this._value = undefined; + } +} +class Persistent { + constructor(value) { + this._ref = new StrongRef(value); + } + setWeak(param, callback) { + if (!supportFinalizer || this._ref === undefined || this._ref instanceof WeakRef) + return; + const value = this._ref.deref(); + try { + Persistent._registry.register(value, this, this); + const weakRef = new WeakRef(value); + this._ref.dispose(); + this._ref = weakRef; + this._param = param; + this._callback = callback; + } + catch (err) { + if (typeof value === 'symbol') ; + else { + throw err; + } + } + } + clearWeak() { + if (!supportFinalizer || this._ref === undefined) + return; + if (this._ref instanceof WeakRef) { + try { + Persistent._registry.unregister(this); + } + catch (_) { } + this._param = undefined; + this._callback = undefined; + const value = this._ref.deref(); + if (value === undefined) { + this._ref = value; + } + else { + this._ref = new StrongRef(value); + } + } + } + reset() { + if (supportFinalizer) { + try { + Persistent._registry.unregister(this); + } + catch (_) { } + } + this._param = undefined; + this._callback = undefined; + if (this._ref instanceof StrongRef) { + this._ref.dispose(); + } + this._ref = undefined; + } + isEmpty() { + return this._ref === undefined; + } + deref() { + if (this._ref === undefined) + return undefined; + return this._ref.deref(); + } +} +Persistent._registry = supportFinalizer + ? new FinalizationRegistry((value) => { + value._ref = undefined; + const callback = value._callback; + const param = value._param; + value._callback = undefined; + value._param = undefined; + if (typeof callback === 'function') { + callback(param); + } + }) + : undefined; + +exports.ReferenceOwnership = void 0; +(function (ReferenceOwnership) { + ReferenceOwnership[ReferenceOwnership["kRuntime"] = 0] = "kRuntime"; + ReferenceOwnership[ReferenceOwnership["kUserland"] = 1] = "kUserland"; +})(exports.ReferenceOwnership || (exports.ReferenceOwnership = {})); +function canBeHeldWeakly(value) { + return value.isObject() || value.isFunction() || value.isSymbol(); +} +class Reference extends RefTracker { + static weakCallback(ref) { + ref.persistent.reset(); + ref.invokeFinalizerFromGC(); + } + static create(envObject, handle_id, initialRefcount, ownership, _unused1, _unused2, _unused3) { + const ref = new Reference(envObject, handle_id, initialRefcount, ownership); + envObject.ctx.refStore.add(ref); + ref.link(envObject.reflist); + return ref; + } + constructor(envObject, handle_id, initialRefcount, ownership) { + super(); + this.envObject = envObject; + this._refcount = initialRefcount; + this._ownership = ownership; + const handle = envObject.ctx.handleStore.get(handle_id); + this.canBeWeak = canBeHeldWeakly(handle); + this.persistent = new Persistent(handle.value); + this.id = 0; + if (initialRefcount === 0) { + this._setWeak(); + } + } + ref() { + if (this.persistent.isEmpty()) { + return 0; + } + if (++this._refcount === 1 && this.canBeWeak) { + this.persistent.clearWeak(); + } + return this._refcount; + } + unref() { + if (this.persistent.isEmpty() || this._refcount === 0) { + return 0; + } + if (--this._refcount === 0) { + this._setWeak(); + } + return this._refcount; + } + get(envObject = this.envObject) { + if (this.persistent.isEmpty()) { + return 0; + } + const obj = this.persistent.deref(); + const handle = envObject.ensureHandle(obj); + return handle.id; + } + resetFinalizer() { } + data() { return 0; } + refcount() { return this._refcount; } + ownership() { return this._ownership; } + callUserFinalizer() { } + invokeFinalizerFromGC() { + this.finalize(); + } + _setWeak() { + if (this.canBeWeak) { + this.persistent.setWeak(this, Reference.weakCallback); + } + else { + this.persistent.reset(); + } + } + finalize() { + this.persistent.reset(); + const deleteMe = this._ownership === exports.ReferenceOwnership.kRuntime; + this.unlink(); + this.callUserFinalizer(); + if (deleteMe) { + this.dispose(); + } + } + dispose() { + if (this.id === 0) + return; + this.unlink(); + this.persistent.reset(); + this.envObject.ctx.refStore.remove(this.id); + super.dispose(); + this.envObject = undefined; + this.id = 0; + } +} +class ReferenceWithData extends Reference { + static create(envObject, value, initialRefcount, ownership, data) { + const reference = new ReferenceWithData(envObject, value, initialRefcount, ownership, data); + envObject.ctx.refStore.add(reference); + reference.link(envObject.reflist); + return reference; + } + constructor(envObject, value, initialRefcount, ownership, _data) { + super(envObject, value, initialRefcount, ownership); + this._data = _data; + } + data() { + return this._data; + } +} +class ReferenceWithFinalizer extends Reference { + static create(envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint) { + const reference = new ReferenceWithFinalizer(envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint); + envObject.ctx.refStore.add(reference); + reference.link(envObject.finalizing_reflist); + return reference; + } + constructor(envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint) { + super(envObject, value, initialRefcount, ownership); + this._finalizer = new Finalizer(envObject, finalize_callback, finalize_data, finalize_hint); + } + resetFinalizer() { + this._finalizer.resetFinalizer(); + } + data() { + return this._finalizer.data(); + } + callUserFinalizer() { + this._finalizer.callFinalizer(); + } + invokeFinalizerFromGC() { + this._finalizer.envObject.invokeFinalizerFromGC(this); + } + dispose() { + if (!this._finalizer) + return; + this._finalizer.envObject.dequeueFinalizer(this); + this._finalizer.dispose(); + super.dispose(); + this._finalizer = undefined; + } +} + +class Deferred { + static create(ctx, value) { + const deferred = new Deferred(ctx, value); + ctx.deferredStore.add(deferred); + return deferred; + } + constructor(ctx, value) { + Object.defineProperties(this, { + id: { + configurable: true, + enumerable: true, + value: 0, + writable: true + }, + ctx: { + configurable: true, + enumerable: true, + value: ctx, + writable: true + }, + value: { + configurable: true, + enumerable: true, + value, + writable: true + } + }); + } + resolve(value) { + this.value.resolve(value); + this.dispose(); + } + reject(reason) { + this.value.reject(reason); + this.dispose(); + } + dispose() { + this.ctx.deferredStore.remove(this.id); + this.id = 0; + this.value = null; + this.ctx = null; + } +} + +class Store { + constructor() { + this._values = [undefined]; + this._values.length = 4; + this._size = 1; + this._freeList = []; + } + add(value) { + let id; + if (this._freeList.length) { + id = this._freeList.shift(); + } + else { + id = this._size; + this._size++; + const capacity = this._values.length; + if (id >= capacity) { + this._values.length = capacity + (capacity >> 1) + 16; + } + } + value.id = id; + this._values[id] = value; + } + get(id) { + return this._values[id]; + } + has(id) { + return this._values[id] !== undefined; + } + remove(id) { + const value = this._values[id]; + if (value) { + value.id = 0; + this._values[id] = undefined; + this._freeList.push(Number(id)); + } + } + dispose() { + for (let i = 1; i < this._size; ++i) { + const value = this._values[i]; + value === null || value === void 0 ? void 0 : value.dispose(); + } + this._values = [undefined]; + this._size = 1; + this._freeList = []; + } +} + +const kMaxReasonableBytes = BigInt(1) << BigInt(60); +const kMinReasonableBytes = -kMaxReasonableBytes; +class ExternalMemory { + constructor(onChange) { + this.total = BigInt(0); + this.onChange = onChange !== null && onChange !== void 0 ? onChange : null; + } + adjust(changeInBytes) { + changeInBytes = BigInt(changeInBytes); + if (!(kMinReasonableBytes <= changeInBytes && changeInBytes < kMaxReasonableBytes)) { + throw new RangeError(`changeInBytes ${changeInBytes} is out of reasonable range`); + } + const old = this.total; + this.total += changeInBytes; + const amount = this.total; + const onChange = this.onChange; + if (changeInBytes) { + onChange === null || onChange === void 0 ? void 0 : onChange(amount, old, changeInBytes); + } + return amount; + } +} + +class CleanupHookCallback { + constructor(envObject, fn, arg, order) { + this.envObject = envObject; + this.fn = fn; + this.arg = arg; + this.order = order; + } +} +class CleanupQueue { + constructor() { + this._cleanupHooks = []; + this._cleanupHookCounter = 0; + } + empty() { + return this._cleanupHooks.length === 0; + } + add(envObject, fn, arg) { + if (this._cleanupHooks.filter((hook) => (hook.envObject === envObject && hook.fn === fn && hook.arg === arg)).length > 0) { + throw new Error('Can not add same fn and arg twice'); + } + this._cleanupHooks.push(new CleanupHookCallback(envObject, fn, arg, this._cleanupHookCounter++)); + } + remove(envObject, fn, arg) { + for (let i = 0; i < this._cleanupHooks.length; ++i) { + const hook = this._cleanupHooks[i]; + if (hook.envObject === envObject && hook.fn === fn && hook.arg === arg) { + this._cleanupHooks.splice(i, 1); + return; + } + } + } + drain() { + const hooks = this._cleanupHooks.slice(); + hooks.sort((a, b) => (b.order - a.order)); + for (let i = 0; i < hooks.length; ++i) { + const cb = hooks[i]; + if (typeof cb.fn === 'number') { + cb.envObject.makeDynCall_vp(cb.fn)(cb.arg); + } + else { + cb.fn(cb.arg); + } + this._cleanupHooks.splice(this._cleanupHooks.indexOf(cb), 1); + } + } + dispose() { + this._cleanupHooks.length = 0; + this._cleanupHookCounter = 0; + } +} +class NodejsWaitingRequestCounter { + constructor() { + this.refHandle = new _MessageChannel().port1; + this.count = 0; + } + increase() { + if (this.count === 0) { + if (this.refHandle.ref) { + this.refHandle.ref(); + } + } + this.count++; + } + decrease() { + if (this.count === 0) + return; + if (this.count === 1) { + if (this.refHandle.unref) { + this.refHandle.unref(); + } + } + this.count--; + } +} +class Context { + constructor(options) { + this._isStopping = false; + this._canCallIntoJs = true; + this._suppressDestroy = false; + this.envStore = new Store(); + this.scopeStore = new ScopeStore(); + this.refStore = new Store(); + this.deferredStore = new Store(); + this.handleStore = new HandleStore(); + this.feature = { + supportReflect, + supportFinalizer, + supportWeakSymbol, + supportBigInt, + supportNewFunction, + canSetFunctionName, + setImmediate: _setImmediate, + Buffer: _Buffer, + MessageChannel: _MessageChannel + }; + this.cleanupQueue = new CleanupQueue(); + this._externalMemory = new ExternalMemory(options === null || options === void 0 ? void 0 : options.onExternalMemoryChange); + if (typeof process === 'object' && process !== null && typeof process.once === 'function') { + this.refCounter = new NodejsWaitingRequestCounter(); + process.once('beforeExit', () => { + if (!this._suppressDestroy) { + this.destroy(); + } + }); + } + } + suppressDestroy() { + this._suppressDestroy = true; + } + getRuntimeVersions() { + return { + version, + NODE_API_SUPPORTED_VERSION_MAX, + NAPI_VERSION_EXPERIMENTAL, + NODE_API_DEFAULT_MODULE_API_VERSION + }; + } + createNotSupportWeakRefError(api, message) { + return new NotSupportWeakRefError(api, message); + } + createNotSupportBufferError(api, message) { + return new NotSupportBufferError(api, message); + } + createReference(envObject, handle_id, initialRefcount, ownership) { + return Reference.create(envObject, handle_id, initialRefcount, ownership); + } + createReferenceWithData(envObject, handle_id, initialRefcount, ownership, data) { + return ReferenceWithData.create(envObject, handle_id, initialRefcount, ownership, data); + } + createReferenceWithFinalizer(envObject, handle_id, initialRefcount, ownership, finalize_callback = 0, finalize_data = 0, finalize_hint = 0) { + return ReferenceWithFinalizer.create(envObject, handle_id, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint); + } + createDeferred(value) { + return Deferred.create(this, value); + } + adjustAmountOfExternalAllocatedMemory(changeInBytes) { + return this._externalMemory.adjust(changeInBytes); + } + createEnv(filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding) { + return newEnv(this, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding); + } + createTrackedFinalizer(envObject, finalize_callback, finalize_data, finalize_hint) { + return TrackedFinalizer.create(envObject, finalize_callback, finalize_data, finalize_hint); + } + getCurrentScope() { + return this.scopeStore.currentScope; + } + addToCurrentScope(value) { + return this.scopeStore.currentScope.add(value); + } + openScope(envObject) { + const scope = this.scopeStore.openScope(this.handleStore); + if (envObject) + envObject.openHandleScopes++; + return scope; + } + closeScope(envObject, _scope) { + if (envObject && envObject.openHandleScopes === 0) + return; + this.scopeStore.closeScope(); + if (envObject) + envObject.openHandleScopes--; + } + ensureHandle(value) { + switch (value) { + case undefined: return HandleStore.UNDEFINED; + case null: return HandleStore.NULL; + case true: return HandleStore.TRUE; + case false: return HandleStore.FALSE; + case _global: return HandleStore.GLOBAL; + } + return this.addToCurrentScope(value); + } + addCleanupHook(envObject, fn, arg) { + this.cleanupQueue.add(envObject, fn, arg); + } + removeCleanupHook(envObject, fn, arg) { + this.cleanupQueue.remove(envObject, fn, arg); + } + runCleanup() { + while (!this.cleanupQueue.empty()) { + this.cleanupQueue.drain(); + } + } + increaseWaitingRequestCounter() { + var _a; + (_a = this.refCounter) === null || _a === void 0 ? void 0 : _a.increase(); + } + decreaseWaitingRequestCounter() { + var _a; + (_a = this.refCounter) === null || _a === void 0 ? void 0 : _a.decrease(); + } + setCanCallIntoJs(value) { + this._canCallIntoJs = value; + } + setStopping(value) { + this._isStopping = value; + } + canCallIntoJs() { + return this._canCallIntoJs && !this._isStopping; + } + destroy() { + this.setStopping(true); + this.setCanCallIntoJs(false); + this.runCleanup(); + } +} +let defaultContext; +function createContext(options) { + return new Context(options); +} +function getDefaultContext() { + if (!defaultContext) { + defaultContext = createContext(); + } + return defaultContext; +} + +exports.ConstHandle = ConstHandle; +exports.Context = Context; +exports.Deferred = Deferred; +exports.EmnapiError = EmnapiError; +exports.Env = Env; +exports.External = External; +exports.Finalizer = Finalizer; +exports.Handle = Handle; +exports.HandleScope = HandleScope; +exports.HandleStore = HandleStore; +exports.NAPI_VERSION_EXPERIMENTAL = NAPI_VERSION_EXPERIMENTAL; +exports.NODE_API_DEFAULT_MODULE_API_VERSION = NODE_API_DEFAULT_MODULE_API_VERSION; +exports.NODE_API_SUPPORTED_VERSION_MAX = NODE_API_SUPPORTED_VERSION_MAX; +exports.NODE_API_SUPPORTED_VERSION_MIN = NODE_API_SUPPORTED_VERSION_MIN; +exports.NodeEnv = NodeEnv; +exports.NotSupportBufferError = NotSupportBufferError; +exports.NotSupportWeakRefError = NotSupportWeakRefError; +exports.Persistent = Persistent; +exports.RefTracker = RefTracker; +exports.Reference = Reference; +exports.ReferenceWithData = ReferenceWithData; +exports.ReferenceWithFinalizer = ReferenceWithFinalizer; +exports.ScopeStore = ScopeStore; +exports.Store = Store; +exports.TrackedFinalizer = TrackedFinalizer; +exports.TryCatch = TryCatch; +exports.createContext = createContext; +exports.getDefaultContext = getDefaultContext; +exports.getExternalValue = getExternalValue; +exports.isExternal = isExternal; +exports.isReferenceType = isReferenceType; +exports.version = version; diff --git a/node_modules/@emnapi/runtime/dist/emnapi.cjs.min.d.ts b/node_modules/@emnapi/runtime/dist/emnapi.cjs.min.d.ts new file mode 100644 index 0000000..c2404e3 --- /dev/null +++ b/node_modules/@emnapi/runtime/dist/emnapi.cjs.min.d.ts @@ -0,0 +1,671 @@ +export declare type Ptr = number | bigint + +export declare interface IBuffer extends Uint8Array {} +export declare interface BufferCtor { + readonly prototype: IBuffer + /** @deprecated */ + new (...args: any[]): IBuffer + from: { + (buffer: ArrayBufferLike): IBuffer + (buffer: ArrayBufferLike, byteOffset: number, length: number): IBuffer + } + alloc: (size: number) => IBuffer + isBuffer: (obj: unknown) => obj is IBuffer +} + +export declare const enum GlobalHandle { + UNDEFINED = 1, + NULL, + FALSE, + TRUE, + GLOBAL +} + +export declare const enum Version { + NODE_API_SUPPORTED_VERSION_MIN = 1, + NODE_API_DEFAULT_MODULE_API_VERSION = 8, + NODE_API_SUPPORTED_VERSION_MAX = 10, + NAPI_VERSION_EXPERIMENTAL = 2147483647 // INT_MAX +} +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export declare type Pointer = number +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export declare type PointerPointer = number +export declare type FunctionPointer any> = Pointer +export declare type Const = T + +export declare type void_p = Pointer +export declare type void_pp = Pointer +export declare type bool = number +export declare type char = number +export declare type char_p = Pointer +export declare type unsigned_char = number +export declare type const_char = Const +export declare type const_char_p = Pointer +export declare type char16_t_p = number +export declare type const_char16_t_p = number + +export declare type short = number +export declare type unsigned_short = number +export declare type int = number +export declare type unsigned_int = number +export declare type long = number +export declare type unsigned_long = number +export declare type long_long = bigint +export declare type unsigned_long_long = bigint +export declare type float = number +export declare type double = number +export declare type long_double = number +export declare type size_t = number + +export declare type int8_t = number +export declare type uint8_t = number +export declare type int16_t = number +export declare type uint16_t = number +export declare type int32_t = number +export declare type uint32_t = number +export declare type int64_t = bigint +export declare type uint64_t = bigint +export declare type napi_env = Pointer + +export declare type napi_value = Pointer +export declare type napi_ref = Pointer +export declare type napi_deferred = Pointer +export declare type napi_handle_scope = Pointer +export declare type napi_escapable_handle_scope = Pointer + +export declare type napi_addon_register_func = FunctionPointer<(env: napi_env, exports: napi_value) => napi_value> + +export declare type napi_callback_info = Pointer +export declare type napi_callback = FunctionPointer<(env: napi_env, info: napi_callback_info) => napi_value> + +export declare interface napi_extended_error_info { + error_message: const_char_p + engine_reserved: void_p + engine_error_code: uint32_t + error_code: napi_status +} + +export declare interface napi_property_descriptor { + // One of utf8name or name should be NULL. + utf8name: const_char_p + name: napi_value + + method: napi_callback + getter: napi_callback + setter: napi_callback + value: napi_value + /* napi_property_attributes */ + attributes: number + data: void_p +} + +export declare type napi_finalize = FunctionPointer<( + env: napi_env, + finalize_data: void_p, + finalize_hint: void_p +) => void> + +export declare interface node_module { + nm_version: int32_t + nm_flags: uint32_t + nm_filename: Pointer + nm_register_func: napi_addon_register_func + nm_modname: Pointer + nm_priv: Pointer + reserved: PointerPointer +} + +export declare interface napi_node_version { + major: uint32_t + minor: uint32_t + patch: uint32_t + release: const_char_p +} + +export declare interface emnapi_emscripten_version { + major: uint32_t + minor: uint32_t + patch: uint32_t +} + +export declare const enum napi_status { + napi_ok, + napi_invalid_arg, + napi_object_expected, + napi_string_expected, + napi_name_expected, + napi_function_expected, + napi_number_expected, + napi_boolean_expected, + napi_array_expected, + napi_generic_failure, + napi_pending_exception, + napi_cancelled, + napi_escape_called_twice, + napi_handle_scope_mismatch, + napi_callback_scope_mismatch, + napi_queue_full, + napi_closing, + napi_bigint_expected, + napi_date_expected, + napi_arraybuffer_expected, + napi_detachable_arraybuffer_expected, + napi_would_deadlock, // unused + napi_no_external_buffers_allowed, + napi_cannot_run_js +} + +export declare const enum napi_property_attributes { + napi_default = 0, + napi_writable = 1 << 0, + napi_enumerable = 1 << 1, + napi_configurable = 1 << 2, + + // Used with napi_define_class to distinguish static properties + // from instance properties. Ignored by napi_define_properties. + napi_static = 1 << 10, + + /// #ifdef NAPI_EXPERIMENTAL + // Default for class methods. + napi_default_method = napi_writable | napi_configurable, + + // Default for object properties, like in JS obj[prop]. + napi_default_jsproperty = napi_writable | napi_enumerable | napi_configurable + /// #endif // NAPI_EXPERIMENTAL +} + +export declare const enum napi_valuetype { + napi_undefined, + napi_null, + napi_boolean, + napi_number, + napi_string, + napi_symbol, + napi_object, + napi_function, + napi_external, + napi_bigint +} + +export declare const enum napi_typedarray_type { + napi_int8_array, + napi_uint8_array, + napi_uint8_clamped_array, + napi_int16_array, + napi_uint16_array, + napi_int32_array, + napi_uint32_array, + napi_float32_array, + napi_float64_array, + napi_bigint64_array, + napi_biguint64_array, + napi_float16_array, +} + +export declare const enum napi_key_collection_mode { + napi_key_include_prototypes, + napi_key_own_only +} + +export declare const enum napi_key_filter { + napi_key_all_properties = 0, + napi_key_writable = 1, + napi_key_enumerable = 1 << 1, + napi_key_configurable = 1 << 2, + napi_key_skip_strings = 1 << 3, + napi_key_skip_symbols = 1 << 4 +} + +export declare const enum napi_key_conversion { + napi_key_keep_numbers, + napi_key_numbers_to_strings +} + +export declare const enum emnapi_memory_view_type { + emnapi_int8_array, + emnapi_uint8_array, + emnapi_uint8_clamped_array, + emnapi_int16_array, + emnapi_uint16_array, + emnapi_int32_array, + emnapi_uint32_array, + emnapi_float32_array, + emnapi_float64_array, + emnapi_bigint64_array, + emnapi_biguint64_array, + emnapi_float16_array, + emnapi_data_view = -1, + emnapi_buffer = -2 +} + +export declare const enum napi_threadsafe_function_call_mode { + napi_tsfn_nonblocking, + napi_tsfn_blocking +} + +export declare const enum napi_threadsafe_function_release_mode { + napi_tsfn_release, + napi_tsfn_abort +} +export declare type CleanupHookCallbackFunction = number | ((arg: number) => void); + +export declare class ConstHandle extends Handle { + constructor(id: number, value: S); + dispose(): void; +} + +export declare class Context { + private _isStopping; + private _canCallIntoJs; + private _suppressDestroy; + envStore: Store; + scopeStore: ScopeStore; + refStore: Store; + deferredStore: Store>; + handleStore: HandleStore; + private readonly refCounter?; + private readonly cleanupQueue; + private readonly _externalMemory; + feature: { + supportReflect: boolean; + supportFinalizer: boolean; + supportWeakSymbol: boolean; + supportBigInt: boolean; + supportNewFunction: boolean; + canSetFunctionName: boolean; + setImmediate: (callback: () => void) => void; + Buffer: BufferCtor | undefined; + MessageChannel: { + new (): MessageChannel; + prototype: MessageChannel; + } | undefined; + }; + constructor(options?: ContextOptions); + /** + * Suppress the destroy on `beforeExit` event in Node.js. + * Call this method if you want to keep the context and + * all associated {@link Env | Env} alive, + * this also means that cleanup hooks will not be called. + * After call this method, you should call + * {@link Context.destroy | `Context.prototype.destroy`} method manually. + */ + suppressDestroy(): void; + getRuntimeVersions(): { + version: string; + NODE_API_SUPPORTED_VERSION_MAX: Version; + NAPI_VERSION_EXPERIMENTAL: Version; + NODE_API_DEFAULT_MODULE_API_VERSION: Version; + }; + createNotSupportWeakRefError(api: string, message: string): NotSupportWeakRefError; + createNotSupportBufferError(api: string, message: string): NotSupportBufferError; + createReference(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership): Reference; + createReferenceWithData(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, data: void_p): Reference; + createReferenceWithFinalizer(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, finalize_callback?: napi_finalize, finalize_data?: void_p, finalize_hint?: void_p): Reference; + createDeferred(value: IDeferrdValue): Deferred; + adjustAmountOfExternalAllocatedMemory(changeInBytes: number | bigint): bigint; + createEnv(filename: string, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never, nodeBinding?: any): Env; + createTrackedFinalizer(envObject: Env, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): TrackedFinalizer; + getCurrentScope(): HandleScope | null; + addToCurrentScope(value: V): Handle; + openScope(envObject?: Env): HandleScope; + closeScope(envObject?: Env, _scope?: HandleScope): void; + ensureHandle(value: S): Handle; + addCleanupHook(envObject: Env, fn: CleanupHookCallbackFunction, arg: number): void; + removeCleanupHook(envObject: Env, fn: CleanupHookCallbackFunction, arg: number): void; + runCleanup(): void; + increaseWaitingRequestCounter(): void; + decreaseWaitingRequestCounter(): void; + setCanCallIntoJs(value: boolean): void; + setStopping(value: boolean): void; + canCallIntoJs(): boolean; + /** + * Destroy the context and call cleanup hooks. + * Associated {@link Env | Env} will be destroyed. + */ + destroy(): void; +} + +export declare interface ContextOptions { + onExternalMemoryChange?: (current: bigint, old: bigint, delta: bigint) => any; +} + +export declare function createContext(options?: ContextOptions): Context; + +export declare class Deferred implements IStoreValue { + static create(ctx: Context, value: IDeferrdValue): Deferred; + id: number; + ctx: Context; + value: IDeferrdValue; + constructor(ctx: Context, value: IDeferrdValue); + resolve(value: T): void; + reject(reason?: any): void; + dispose(): void; +} + +export declare class EmnapiError extends Error { + constructor(message?: string); +} + +export declare abstract class Env implements IStoreValue { + readonly ctx: Context; + moduleApiVersion: number; + makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void; + makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void; + abort: (msg?: string) => never; + id: number; + openHandleScopes: number; + instanceData: TrackedFinalizer | null; + tryCatch: TryCatch; + refs: number; + reflist: RefTracker; + finalizing_reflist: RefTracker; + pendingFinalizers: RefTracker[]; + lastError: { + errorCode: napi_status; + engineErrorCode: number; + engineReserved: Ptr; + }; + inGcFinalizer: boolean; + constructor(ctx: Context, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never); + /** @virtual */ + canCallIntoJs(): boolean; + terminatedOrTerminating(): boolean; + ref(): void; + unref(): void; + ensureHandle(value: S): Handle; + ensureHandleId(value: any): napi_value; + clearLastError(): napi_status; + setLastError(error_code: napi_status, engine_error_code?: uint32_t, engine_reserved?: void_p): napi_status; + getReturnStatus(): napi_status; + callIntoModule(fn: (env: Env) => T, handleException?: (envObject: Env, value: any) => void): T; + /** @virtual */ + abstract callFinalizer(cb: napi_finalize, data: void_p, hint: void_p): void; + invokeFinalizerFromGC(finalizer: RefTracker): void; + checkGCAccess(): void; + /** @virtual */ + enqueueFinalizer(finalizer: RefTracker): void; + /** @virtual */ + dequeueFinalizer(finalizer: RefTracker): void; + /** @virtual */ + deleteMe(): void; + dispose(): void; + private readonly _bindingMap; + initObjectBinding(value: S): IReferenceBinding; + getObjectBinding(value: S): IReferenceBinding; + setInstanceData(data: number, finalize_cb: number, finalize_hint: number): void; + getInstanceData(): number; +} + +/** @public */ +declare interface External_2 extends Record { +} + +/** @public */ +declare const External_2: { + new (value: number | bigint): External_2; + prototype: null; +}; +export { External_2 as External } + +export declare class Finalizer { + envObject: Env; + private _finalizeCallback; + private _finalizeData; + private _finalizeHint; + private _makeDynCall_vppp; + constructor(envObject: Env, _finalizeCallback?: napi_finalize, _finalizeData?: void_p, _finalizeHint?: void_p); + callback(): napi_finalize; + data(): void_p; + hint(): void_p; + resetEnv(): void; + resetFinalizer(): void; + callFinalizer(): void; + dispose(): void; +} + +export declare function getDefaultContext(): Context; + +/** @public */ +export declare function getExternalValue(external: External_2): number | bigint; + +export declare class Handle { + id: number; + value: S; + constructor(id: number, value: S); + data(): void_p; + isNumber(): boolean; + isBigInt(): boolean; + isString(): boolean; + isFunction(): boolean; + isExternal(): boolean; + isObject(): boolean; + isArray(): boolean; + isArrayBuffer(): boolean; + isTypedArray(): boolean; + isBuffer(BufferConstructor?: BufferCtor): boolean; + isDataView(): boolean; + isDate(): boolean; + isPromise(): boolean; + isBoolean(): boolean; + isUndefined(): boolean; + isSymbol(): boolean; + isNull(): boolean; + dispose(): void; +} + +export declare class HandleScope { + handleStore: HandleStore; + id: number; + parent: HandleScope | null; + child: HandleScope | null; + start: number; + end: number; + private _escapeCalled; + callbackInfo: ICallbackInfo; + constructor(handleStore: HandleStore, id: number, parentScope: HandleScope | null, start: number, end?: number); + add(value: V): Handle; + addExternal(data: void_p): Handle; + dispose(): void; + escape(handle: number): Handle | null; + escapeCalled(): boolean; +} + +export declare class HandleStore { + static UNDEFINED: ConstHandle; + static NULL: ConstHandle; + static FALSE: ConstHandle; + static TRUE: ConstHandle; + static GLOBAL: ConstHandle; + static MIN_ID: 6; + private readonly _values; + private _next; + push(value: S): Handle; + erase(start: number, end: number): void; + get(id: Ptr): Handle | undefined; + swap(a: number, b: number): void; + dispose(): void; +} + +export declare interface ICallbackInfo { + thiz: any; + data: void_p; + args: ArrayLike; + fn: Function; +} + +export declare interface IDeferrdValue { + resolve: (value: T) => void; + reject: (reason?: any) => void; +} + +export declare interface IReferenceBinding { + wrapped: number; + tag: Uint32Array | null; +} + +/** @public */ +export declare function isExternal(object: unknown): object is External_2; + +export declare function isReferenceType(v: any): v is object; + +export declare interface IStoreValue { + id: number; + dispose(): void; + [x: string]: any; +} + +export declare const NAPI_VERSION_EXPERIMENTAL = Version.NAPI_VERSION_EXPERIMENTAL; + +export declare const NODE_API_DEFAULT_MODULE_API_VERSION = Version.NODE_API_DEFAULT_MODULE_API_VERSION; + +export declare const NODE_API_SUPPORTED_VERSION_MAX = Version.NODE_API_SUPPORTED_VERSION_MAX; + +export declare const NODE_API_SUPPORTED_VERSION_MIN = Version.NODE_API_SUPPORTED_VERSION_MIN; + +export declare class NodeEnv extends Env { + filename: string; + private readonly nodeBinding?; + destructing: boolean; + finalizationScheduled: boolean; + constructor(ctx: Context, filename: string, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never, nodeBinding?: any); + deleteMe(): void; + canCallIntoJs(): boolean; + triggerFatalException(err: any): void; + callbackIntoModule(enforceUncaughtExceptionPolicy: boolean, fn: (env: Env) => T): T; + callFinalizer(cb: napi_finalize, data: void_p, hint: void_p): void; + callFinalizerInternal(forceUncaught: int, cb: napi_finalize, data: void_p, hint: void_p): void; + enqueueFinalizer(finalizer: RefTracker): void; + drainFinalizerQueue(): void; +} + +export declare class NotSupportBufferError extends EmnapiError { + constructor(api: string, message: string); +} + +export declare class NotSupportWeakRefError extends EmnapiError { + constructor(api: string, message: string); +} + +export declare class Persistent { + private _ref; + private _param; + private _callback; + private static readonly _registry; + constructor(value: T); + setWeak

(param: P, callback: (param: P) => void): void; + clearWeak(): void; + reset(): void; + isEmpty(): boolean; + deref(): T | undefined; +} + +export declare class Reference extends RefTracker implements IStoreValue { + private static weakCallback; + id: number; + envObject: Env; + private readonly canBeWeak; + private _refcount; + private readonly _ownership; + persistent: Persistent; + static create(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, _unused1?: void_p, _unused2?: void_p, _unused3?: void_p): Reference; + protected constructor(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership); + ref(): number; + unref(): number; + get(envObject?: Env): napi_value; + /** @virtual */ + resetFinalizer(): void; + /** @virtual */ + data(): void_p; + refcount(): number; + ownership(): ReferenceOwnership; + /** @virtual */ + protected callUserFinalizer(): void; + /** @virtual */ + protected invokeFinalizerFromGC(): void; + private _setWeak; + finalize(): void; + dispose(): void; +} + +export declare enum ReferenceOwnership { + kRuntime = 0, + kUserland = 1 +} + +export declare class ReferenceWithData extends Reference { + private readonly _data; + static create(envObject: Env, value: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, data: void_p): ReferenceWithData; + private constructor(); + data(): void_p; +} + +export declare class ReferenceWithFinalizer extends Reference { + private _finalizer; + static create(envObject: Env, value: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): ReferenceWithFinalizer; + private constructor(); + resetFinalizer(): void; + data(): void_p; + protected callUserFinalizer(): void; + protected invokeFinalizerFromGC(): void; + dispose(): void; +} + +export declare class RefTracker { + /** @virtual */ + dispose(): void; + /** @virtual */ + finalize(): void; + private _next; + private _prev; + link(list: RefTracker): void; + unlink(): void; + static finalizeAll(list: RefTracker): void; +} + +export declare class ScopeStore { + private readonly _rootScope; + currentScope: HandleScope; + private readonly _values; + constructor(); + get(id: number): HandleScope | undefined; + openScope(handleStore: HandleStore): HandleScope; + closeScope(): void; + dispose(): void; +} + +export declare class Store { + protected _values: Array; + private _freeList; + private _size; + constructor(); + add(value: V): void; + get(id: Ptr): V | undefined; + has(id: Ptr): boolean; + remove(id: Ptr): void; + dispose(): void; +} + +export declare class TrackedFinalizer extends RefTracker { + private _finalizer; + static create(envObject: Env, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): TrackedFinalizer; + private constructor(); + data(): void_p; + dispose(): void; + finalize(): void; +} + +export declare class TryCatch { + private _exception; + private _caught; + isEmpty(): boolean; + hasCaught(): boolean; + exception(): any; + setError(err: any): void; + reset(): void; + extractException(): any; +} + +export declare const version: string; + +export { } diff --git a/node_modules/@emnapi/runtime/dist/emnapi.cjs.min.js b/node_modules/@emnapi/runtime/dist/emnapi.cjs.min.js new file mode 100644 index 0000000..32aaf71 --- /dev/null +++ b/node_modules/@emnapi/runtime/dist/emnapi.cjs.min.js @@ -0,0 +1 @@ +const e=new WeakMap;function t(t){return e.has(t)}const i=(()=>{function t(t){Object.setPrototypeOf(this,null),e.set(this,t)}return t.prototype=null,t})();function s(i){if(!t(i))throw new TypeError("not external");return e.get(i)}const n=function(){let e;try{e=new Function}catch(e){return!1}return"function"==typeof e}(),r=function(){if("undefined"!=typeof globalThis)return globalThis;let e=function(){return this}();if(!e&&n)try{e=new Function("return this")()}catch(e){}if(!e){if("undefined"==typeof __webpack_public_path__&&"undefined"!=typeof global)return global;if("undefined"!=typeof window)return window;if("undefined"!=typeof self)return self}return e}();class o{constructor(){this._exception=void 0,this._caught=!1}isEmpty(){return!this._caught}hasCaught(){return this._caught}exception(){return this._exception}setError(e){this._caught=!0,this._exception=e}reset(){this._caught=!1,this._exception=void 0}extractException(){const e=this._exception;return this.reset(),e}}const a=function(){var e;try{return Boolean(null===(e=Object.getOwnPropertyDescriptor(Function.prototype,"name"))||void 0===e?void 0:e.configurable)}catch(e){return!1}}(),l="object"==typeof Reflect,c="undefined"!=typeof FinalizationRegistry&&"undefined"!=typeof WeakRef,u=function(){try{const e=Symbol();new WeakRef(e),(new WeakMap).set(e,void 0)}catch(e){return!1}return!0}(),h="undefined"!=typeof BigInt;const p=function(){let e;return e="undefined"!=typeof __webpack_public_path__||"undefined"!=typeof __webpack_public_path__?"undefined"!=typeof __non_webpack_require__?__non_webpack_require__:void 0:"undefined"!=typeof require?require:void 0,e}(),f="function"==typeof MessageChannel?MessageChannel:function(){try{return p("worker_threads").MessageChannel}catch(e){}}(),d="function"==typeof setImmediate?setImmediate.bind(r):function(e){if("function"!=typeof e)throw new TypeError('The "callback" argument must be of type function');if(f){let t=new f;t.port1.onmessage=function(){t.port1.onmessage=null,t=void 0,e()},t.port2.postMessage(null)}else setTimeout(e,0)},_="function"==typeof Buffer?Buffer:function(){try{return p("buffer").Buffer}catch(e){}}(),v="1.11.3",g=2147483647;class y{constructor(e,t){this.id=e,this.value=t}data(){return s(this.value)}isNumber(){return"number"==typeof this.value}isBigInt(){return"bigint"==typeof this.value}isString(){return"string"==typeof this.value}isFunction(){return"function"==typeof this.value}isExternal(){return t(this.value)}isObject(){return"object"==typeof this.value&&null!==this.value}isArray(){return Array.isArray(this.value)}isArrayBuffer(){return this.value instanceof ArrayBuffer}isTypedArray(){return ArrayBuffer.isView(this.value)&&!(this.value instanceof DataView)}isBuffer(e){return!!ArrayBuffer.isView(this.value)||(null!=e||(e=_),"function"==typeof e&&e.isBuffer(this.value))}isDataView(){return this.value instanceof DataView}isDate(){return this.value instanceof Date}isPromise(){return this.value instanceof Promise}isBoolean(){return"boolean"==typeof this.value}isUndefined(){return void 0===this.value}isSymbol(){return"symbol"==typeof this.value}isNull(){return null===this.value}dispose(){this.value=void 0}}class x extends y{constructor(e,t){super(e,t)}dispose(){}}class b{constructor(){this._values=[void 0,b.UNDEFINED,b.NULL,b.FALSE,b.TRUE,b.GLOBAL],this._next=b.MIN_ID}push(e){let t;const i=this._next,s=this._values;return i=this.end)return null;this.handleStore.swap(e,this.start);const t=this.handleStore.get(this.start);return this.start++,this.parent.end++,t}escapeCalled(){return this._escapeCalled}}class w{constructor(){this._rootScope=new z(null,0,null,1,b.MIN_ID),this.currentScope=this._rootScope,this._values=[void 0]}get(e){return this._values[e]}openScope(e){const t=this.currentScope;let i=t.child;if(null!==i)i.start=i.end=t.end;else{const s=t.id+1;i=new z(e,s,t,t.end),this._values[s]=i}return this.currentScope=i,i}closeScope(){const e=this.currentScope;this.currentScope=e.parent,e.dispose()}dispose(){this.currentScope=this._rootScope,this._values.length=1}}class k{constructor(){this._next=null,this._prev=null}dispose(){}finalize(){}link(e){this._prev=e,this._next=e._next,null!==this._next&&(this._next._prev=this),e._next=this}unlink(){null!==this._prev&&(this._prev._next=this._next),null!==this._next&&(this._next._prev=this._prev),this._prev=null,this._next=null}static finalizeAll(e){for(;null!==e._next;)e._next.finalize()}}class m{constructor(e,t=0,i=0,s=0){this.envObject=e,this._finalizeCallback=t,this._finalizeData=i,this._finalizeHint=s,this._makeDynCall_vppp=e.makeDynCall_vppp}callback(){return this._finalizeCallback}data(){return this._finalizeData}hint(){return this._finalizeHint}resetEnv(){this.envObject=void 0}resetFinalizer(){this._finalizeCallback=0,this._finalizeData=0,this._finalizeHint=0}callFinalizer(){const e=this._finalizeCallback,t=this._finalizeData,i=this._finalizeHint;if(this.resetFinalizer(),!e)return;const s=Number(e);this.envObject?this.envObject.callFinalizer(s,t,i):this._makeDynCall_vppp(s)(0,t,i)}dispose(){this.envObject=void 0,this._makeDynCall_vppp=void 0}}class E extends k{static create(e,t,i,s){const n=new E(e,t,i,s);return n.link(e.finalizing_reflist),n}constructor(e,t,i,s){super(),this._finalizer=new m(e,t,i,s)}data(){return this._finalizer.data()}dispose(){this._finalizer&&(this.unlink(),this._finalizer.envObject.dequeueFinalizer(this),this._finalizer.dispose(),this._finalizer=void 0,super.dispose())}finalize(){let e;this.unlink();let t=!1;try{this._finalizer.callFinalizer()}catch(i){t=!0,e=i}if(this.dispose(),t)throw e}}function S(e,t){if(!e.terminatedOrTerminating())throw t}class C{constructor(e,t,i,s,n){this.ctx=e,this.moduleApiVersion=t,this.makeDynCall_vppp=i,this.makeDynCall_vp=s,this.abort=n,this.openHandleScopes=0,this.instanceData=null,this.tryCatch=new o,this.refs=1,this.reflist=new k,this.finalizing_reflist=new k,this.pendingFinalizers=[],this.lastError={errorCode:0,engineErrorCode:0,engineReserved:0},this.inGcFinalizer=!1,this._bindingMap=new WeakMap,this.id=0}canCallIntoJs(){return!0}terminatedOrTerminating(){return!this.canCallIntoJs()}ref(){this.refs++}unref(){this.refs--,0===this.refs&&this.dispose()}ensureHandle(e){return this.ctx.ensureHandle(e)}ensureHandleId(e){return this.ensureHandle(e).id}clearLastError(){const e=this.lastError;return 0!==e.errorCode&&(e.errorCode=0),0!==e.engineErrorCode&&(e.engineErrorCode=0),0!==e.engineReserved&&(e.engineReserved=0),0}setLastError(e,t=0,i=0){const s=this.lastError;return s.errorCode!==e&&(s.errorCode=e),s.engineErrorCode!==t&&(s.engineErrorCode=t),s.engineReserved!==i&&(s.engineReserved=i),e}getReturnStatus(){return this.tryCatch.hasCaught()?this.setLastError(10):0}callIntoModule(e,t=S){const i=this.openHandleScopes;this.clearLastError();const s=e(this);if(i!==this.openHandleScopes&&this.abort("open_handle_scopes != open_handle_scopes_before"),this.tryCatch.hasCaught()){t(this,this.tryCatch.extractException())}return s}invokeFinalizerFromGC(e){if(this.moduleApiVersion!==g)this.enqueueFinalizer(e);else{const t=this.inGcFinalizer;this.inGcFinalizer=!0;try{e.finalize()}finally{this.inGcFinalizer=t}}}checkGCAccess(){this.moduleApiVersion===g&&this.inGcFinalizer&&this.abort("Finalizer is calling a function that may affect GC state.\nThe finalizers are run directly from GC and must not affect GC state.\nUse `node_api_post_finalizer` from inside of the finalizer to work around this issue.\nIt schedules the call as a new task in the event loop.")}enqueueFinalizer(e){-1===this.pendingFinalizers.indexOf(e)&&this.pendingFinalizers.push(e)}dequeueFinalizer(e){const t=this.pendingFinalizers.indexOf(e);-1!==t&&this.pendingFinalizers.splice(t,1)}deleteMe(){k.finalizeAll(this.finalizing_reflist),k.finalizeAll(this.reflist),this.tryCatch.extractException(),this.ctx.envStore.remove(this.id)}dispose(){0!==this.id&&(this.deleteMe(),this.finalizing_reflist.dispose(),this.reflist.dispose(),this.id=0)}initObjectBinding(e){const t={wrapped:0,tag:null};return this._bindingMap.set(e,t),t}getObjectBinding(e){return this._bindingMap.has(e)?this._bindingMap.get(e):this.initObjectBinding(e)}setInstanceData(e,t,i){this.instanceData&&this.instanceData.dispose(),this.instanceData=E.create(this,t,e,i)}getInstanceData(){return this.instanceData?this.instanceData.data():0}}class F extends C{constructor(e,t,i,s,n,r,o){super(e,i,s,n,r),this.filename=t,this.nodeBinding=o,this.destructing=!1,this.finalizationScheduled=!1}deleteMe(){this.destructing=!0,this.drainFinalizerQueue(),super.deleteMe()}canCallIntoJs(){return super.canCallIntoJs()&&this.ctx.canCallIntoJs()}triggerFatalException(e){if(this.nodeBinding)this.nodeBinding.napi.fatalException(e);else{if("object"!=typeof process||null===process||"function"!=typeof process._fatalException)throw e;process._fatalException(e)||(console.error(e),process.exit(1))}}callbackIntoModule(e,t){return this.callIntoModule(t,(t,i)=>{if(t.terminatedOrTerminating())return;const s="object"==typeof process&&null!==process,n=!!s&&Boolean(process.execArgv&&-1!==process.execArgv.indexOf("--force-node-api-uncaught-exceptions-policy"));if(t.moduleApiVersion<10&&!n&&!e){return void(s&&"function"==typeof process.emitWarning?process.emitWarning:function(e,t,i){if(e instanceof Error)console.warn(e.toString());else{const s=i?`[${i}] `:"";console.warn(`${s}${t||"Warning"}: ${e}`)}})("Uncaught Node-API callback exception detected, please run node with option --force-node-api-uncaught-exceptions-policy=true to handle those exceptions properly.","DeprecationWarning","DEP0168")}t.triggerFatalException(i)})}callFinalizer(e,t,i){this.callFinalizerInternal(1,e,t,i)}callFinalizerInternal(e,t,i,s){const n=this.makeDynCall_vppp(t),r=this.id,o=this.ctx.openScope(this);try{this.callbackIntoModule(Boolean(e),()=>{n(r,i,s)})}finally{this.ctx.closeScope(this,o)}}enqueueFinalizer(e){super.enqueueFinalizer(e),this.finalizationScheduled||this.destructing||(this.finalizationScheduled=!0,this.ref(),d(()=>{this.finalizationScheduled=!1,this.unref(),this.drainFinalizerQueue()}))}drainFinalizerQueue(){for(;this.pendingFinalizers.length>0;){this.pendingFinalizers.shift().finalize()}}}function I(e,t,i,s,n,r,o){(i="number"!=typeof i?8:i)<8?i=8:i>10&&i!==g&&function(e,t){throw new Error(`${e} requires Node-API version ${t}, but this version of Node.js only supports version 10 add-ons.`)}(t,i);const a=new F(e,t,i,s,n,r,o);return e.envStore.add(a),e.addCleanupHook(a,()=>{a.unref()},0),a}class O extends Error{constructor(e){super(e);const t=new.target,i=t.prototype;if(!(this instanceof O)){const e=Object.setPrototypeOf;"function"==typeof e?e.call(Object,this,i):this.__proto__=i,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,t)}}}Object.defineProperty(O.prototype,"name",{configurable:!0,writable:!0,value:"EmnapiError"});class D extends O{constructor(e,t){super(`${e}: The current runtime does not support "FinalizationRegistry" and "WeakRef".${t?` ${t}`:""}`)}}Object.defineProperty(D.prototype,"name",{configurable:!0,writable:!0,value:"NotSupportWeakRefError"});class R extends O{constructor(e,t){super(`${e}: The current runtime does not support "Buffer". Consider using buffer polyfill to make sure \`globalThis.Buffer\` is defined.${t?` ${t}`:""}`)}}Object.defineProperty(R.prototype,"name",{configurable:!0,writable:!0,value:"NotSupportBufferError"});class N{constructor(e){this._value=e}deref(){return this._value}dispose(){this._value=void 0}}class A{constructor(e){this._ref=new N(e)}setWeak(e,t){if(!c||void 0===this._ref||this._ref instanceof WeakRef)return;const i=this._ref.deref();try{A._registry.register(i,this,this);const s=new WeakRef(i);this._ref.dispose(),this._ref=s,this._param=e,this._callback=t}catch(e){if("symbol"!=typeof i)throw e}}clearWeak(){if(c&&void 0!==this._ref&&this._ref instanceof WeakRef){try{A._registry.unregister(this)}catch(e){}this._param=void 0,this._callback=void 0;const e=this._ref.deref();this._ref=void 0===e?e:new N(e)}}reset(){if(c)try{A._registry.unregister(this)}catch(e){}this._param=void 0,this._callback=void 0,this._ref instanceof N&&this._ref.dispose(),this._ref=void 0}isEmpty(){return void 0===this._ref}deref(){if(void 0!==this._ref)return this._ref.deref()}}var H;A._registry=c?new FinalizationRegistry(e=>{e._ref=void 0;const t=e._callback,i=e._param;e._callback=void 0,e._param=void 0,"function"==typeof t&&t(i)}):void 0,exports.ReferenceOwnership=void 0,(H=exports.ReferenceOwnership||(exports.ReferenceOwnership={}))[H.kRuntime=0]="kRuntime",H[H.kUserland=1]="kUserland";class j extends k{static weakCallback(e){e.persistent.reset(),e.invokeFinalizerFromGC()}static create(e,t,i,s,n,r,o){const a=new j(e,t,i,s);return e.ctx.refStore.add(a),a.link(e.reflist),a}constructor(e,t,i,s){super(),this.envObject=e,this._refcount=i,this._ownership=s;const n=e.ctx.handleStore.get(t);var r;this.canBeWeak=(r=n).isObject()||r.isFunction()||r.isSymbol(),this.persistent=new A(n.value),this.id=0,0===i&&this._setWeak()}ref(){return this.persistent.isEmpty()?0:(1===++this._refcount&&this.canBeWeak&&this.persistent.clearWeak(),this._refcount)}unref(){return this.persistent.isEmpty()||0===this._refcount?0:(0===--this._refcount&&this._setWeak(),this._refcount)}get(e=this.envObject){if(this.persistent.isEmpty())return 0;const t=this.persistent.deref();return e.ensureHandle(t).id}resetFinalizer(){}data(){return 0}refcount(){return this._refcount}ownership(){return this._ownership}callUserFinalizer(){}invokeFinalizerFromGC(){this.finalize()}_setWeak(){this.canBeWeak?this.persistent.setWeak(this,j.weakCallback):this.persistent.reset()}finalize(){this.persistent.reset();const e=this._ownership===exports.ReferenceOwnership.kRuntime;this.unlink(),this.callUserFinalizer(),e&&this.dispose()}dispose(){0!==this.id&&(this.unlink(),this.persistent.reset(),this.envObject.ctx.refStore.remove(this.id),super.dispose(),this.envObject=void 0,this.id=0)}}class B extends j{static create(e,t,i,s,n){const r=new B(e,t,i,s,n);return e.ctx.refStore.add(r),r.link(e.reflist),r}constructor(e,t,i,s,n){super(e,t,i,s),this._data=n}data(){return this._data}}class M extends j{static create(e,t,i,s,n,r,o){const a=new M(e,t,i,s,n,r,o);return e.ctx.refStore.add(a),a.link(e.finalizing_reflist),a}constructor(e,t,i,s,n,r,o){super(e,t,i,s),this._finalizer=new m(e,n,r,o)}resetFinalizer(){this._finalizer.resetFinalizer()}data(){return this._finalizer.data()}callUserFinalizer(){this._finalizer.callFinalizer()}invokeFinalizerFromGC(){this._finalizer.envObject.invokeFinalizerFromGC(this)}dispose(){this._finalizer&&(this._finalizer.envObject.dequeueFinalizer(this),this._finalizer.dispose(),super.dispose(),this._finalizer=void 0)}}class T{static create(e,t){const i=new T(e,t);return e.deferredStore.add(i),i}constructor(e,t){Object.defineProperties(this,{id:{configurable:!0,enumerable:!0,value:0,writable:!0},ctx:{configurable:!0,enumerable:!0,value:e,writable:!0},value:{configurable:!0,enumerable:!0,value:t,writable:!0}})}resolve(e){this.value.resolve(e),this.dispose()}reject(e){this.value.reject(e),this.dispose()}dispose(){this.ctx.deferredStore.remove(this.id),this.id=0,this.value=null,this.ctx=null}}class W{constructor(){this._values=[void 0],this._values.length=4,this._size=1,this._freeList=[]}add(e){let t;if(this._freeList.length)t=this._freeList.shift();else{t=this._size,this._size++;const e=this._values.length;t>=e&&(this._values.length=e+(e>>1)+16)}e.id=t,this._values[t]=e}get(e){return this._values[e]}has(e){return void 0!==this._values[e]}remove(e){const t=this._values[e];t&&(t.id=0,this._values[e]=void 0,this._freeList.push(Number(e)))}dispose(){for(let e=1;es.envObject===e&&s.fn===t&&s.arg===i).length>0)throw new Error("Can not add same fn and arg twice");this._cleanupHooks.push(new V(e,t,i,this._cleanupHookCounter++))}remove(e,t,i){for(let s=0;st.order-e.order);for(let t=0;t{this._suppressDestroy||this.destroy()}))}suppressDestroy(){this._suppressDestroy=!0}getRuntimeVersions(){return{version:v,NODE_API_SUPPORTED_VERSION_MAX:10,NAPI_VERSION_EXPERIMENTAL:g,NODE_API_DEFAULT_MODULE_API_VERSION:8}}createNotSupportWeakRefError(e,t){return new D(e,t)}createNotSupportBufferError(e,t){return new R(e,t)}createReference(e,t,i,s){return j.create(e,t,i,s)}createReferenceWithData(e,t,i,s,n){return B.create(e,t,i,s,n)}createReferenceWithFinalizer(e,t,i,s,n=0,r=0,o=0){return M.create(e,t,i,s,n,r,o)}createDeferred(e){return T.create(this,e)}adjustAmountOfExternalAllocatedMemory(e){return this._externalMemory.adjust(e)}createEnv(e,t,i,s,n,r){return I(this,e,t,i,s,n,r)}createTrackedFinalizer(e,t,i,s){return E.create(e,t,i,s)}getCurrentScope(){return this.scopeStore.currentScope}addToCurrentScope(e){return this.scopeStore.currentScope.add(e)}openScope(e){const t=this.scopeStore.openScope(this.handleStore);return e&&e.openHandleScopes++,t}closeScope(e,t){e&&0===e.openHandleScopes||(this.scopeStore.closeScope(),e&&e.openHandleScopes--)}ensureHandle(e){switch(e){case void 0:return b.UNDEFINED;case null:return b.NULL;case!0:return b.TRUE;case!1:return b.FALSE;case r:return b.GLOBAL}return this.addToCurrentScope(e)}addCleanupHook(e,t,i){this.cleanupQueue.add(e,t,i)}removeCleanupHook(e,t,i){this.cleanupQueue.remove(e,t,i)}runCleanup(){for(;!this.cleanupQueue.empty();)this.cleanupQueue.drain()}increaseWaitingRequestCounter(){var e;null===(e=this.refCounter)||void 0===e||e.increase()}decreaseWaitingRequestCounter(){var e;null===(e=this.refCounter)||void 0===e||e.decrease()}setCanCallIntoJs(e){this._canCallIntoJs=e}setStopping(e){this._isStopping=e}canCallIntoJs(){return this._canCallIntoJs&&!this._isStopping}destroy(){this.setStopping(!0),this.setCanCallIntoJs(!1),this.runCleanup()}}let J;function Q(e){return new $(e)}exports.ConstHandle=x,exports.Context=$,exports.Deferred=T,exports.EmnapiError=O,exports.Env=C,exports.External=i,exports.Finalizer=m,exports.Handle=y,exports.HandleScope=z,exports.HandleStore=b,exports.NAPI_VERSION_EXPERIMENTAL=g,exports.NODE_API_DEFAULT_MODULE_API_VERSION=8,exports.NODE_API_SUPPORTED_VERSION_MAX=10,exports.NODE_API_SUPPORTED_VERSION_MIN=1,exports.NodeEnv=F,exports.NotSupportBufferError=R,exports.NotSupportWeakRefError=D,exports.Persistent=A,exports.RefTracker=k,exports.Reference=j,exports.ReferenceWithData=B,exports.ReferenceWithFinalizer=M,exports.ScopeStore=w,exports.Store=W,exports.TrackedFinalizer=E,exports.TryCatch=o,exports.createContext=Q,exports.getDefaultContext=function(){return J||(J=Q()),J},exports.getExternalValue=s,exports.isExternal=t,exports.isReferenceType=function(e){return"object"==typeof e&&null!==e||"function"==typeof e},exports.version=v; diff --git a/node_modules/@emnapi/runtime/dist/emnapi.d.mts b/node_modules/@emnapi/runtime/dist/emnapi.d.mts new file mode 100644 index 0000000..c2404e3 --- /dev/null +++ b/node_modules/@emnapi/runtime/dist/emnapi.d.mts @@ -0,0 +1,671 @@ +export declare type Ptr = number | bigint + +export declare interface IBuffer extends Uint8Array {} +export declare interface BufferCtor { + readonly prototype: IBuffer + /** @deprecated */ + new (...args: any[]): IBuffer + from: { + (buffer: ArrayBufferLike): IBuffer + (buffer: ArrayBufferLike, byteOffset: number, length: number): IBuffer + } + alloc: (size: number) => IBuffer + isBuffer: (obj: unknown) => obj is IBuffer +} + +export declare const enum GlobalHandle { + UNDEFINED = 1, + NULL, + FALSE, + TRUE, + GLOBAL +} + +export declare const enum Version { + NODE_API_SUPPORTED_VERSION_MIN = 1, + NODE_API_DEFAULT_MODULE_API_VERSION = 8, + NODE_API_SUPPORTED_VERSION_MAX = 10, + NAPI_VERSION_EXPERIMENTAL = 2147483647 // INT_MAX +} +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export declare type Pointer = number +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export declare type PointerPointer = number +export declare type FunctionPointer any> = Pointer +export declare type Const = T + +export declare type void_p = Pointer +export declare type void_pp = Pointer +export declare type bool = number +export declare type char = number +export declare type char_p = Pointer +export declare type unsigned_char = number +export declare type const_char = Const +export declare type const_char_p = Pointer +export declare type char16_t_p = number +export declare type const_char16_t_p = number + +export declare type short = number +export declare type unsigned_short = number +export declare type int = number +export declare type unsigned_int = number +export declare type long = number +export declare type unsigned_long = number +export declare type long_long = bigint +export declare type unsigned_long_long = bigint +export declare type float = number +export declare type double = number +export declare type long_double = number +export declare type size_t = number + +export declare type int8_t = number +export declare type uint8_t = number +export declare type int16_t = number +export declare type uint16_t = number +export declare type int32_t = number +export declare type uint32_t = number +export declare type int64_t = bigint +export declare type uint64_t = bigint +export declare type napi_env = Pointer + +export declare type napi_value = Pointer +export declare type napi_ref = Pointer +export declare type napi_deferred = Pointer +export declare type napi_handle_scope = Pointer +export declare type napi_escapable_handle_scope = Pointer + +export declare type napi_addon_register_func = FunctionPointer<(env: napi_env, exports: napi_value) => napi_value> + +export declare type napi_callback_info = Pointer +export declare type napi_callback = FunctionPointer<(env: napi_env, info: napi_callback_info) => napi_value> + +export declare interface napi_extended_error_info { + error_message: const_char_p + engine_reserved: void_p + engine_error_code: uint32_t + error_code: napi_status +} + +export declare interface napi_property_descriptor { + // One of utf8name or name should be NULL. + utf8name: const_char_p + name: napi_value + + method: napi_callback + getter: napi_callback + setter: napi_callback + value: napi_value + /* napi_property_attributes */ + attributes: number + data: void_p +} + +export declare type napi_finalize = FunctionPointer<( + env: napi_env, + finalize_data: void_p, + finalize_hint: void_p +) => void> + +export declare interface node_module { + nm_version: int32_t + nm_flags: uint32_t + nm_filename: Pointer + nm_register_func: napi_addon_register_func + nm_modname: Pointer + nm_priv: Pointer + reserved: PointerPointer +} + +export declare interface napi_node_version { + major: uint32_t + minor: uint32_t + patch: uint32_t + release: const_char_p +} + +export declare interface emnapi_emscripten_version { + major: uint32_t + minor: uint32_t + patch: uint32_t +} + +export declare const enum napi_status { + napi_ok, + napi_invalid_arg, + napi_object_expected, + napi_string_expected, + napi_name_expected, + napi_function_expected, + napi_number_expected, + napi_boolean_expected, + napi_array_expected, + napi_generic_failure, + napi_pending_exception, + napi_cancelled, + napi_escape_called_twice, + napi_handle_scope_mismatch, + napi_callback_scope_mismatch, + napi_queue_full, + napi_closing, + napi_bigint_expected, + napi_date_expected, + napi_arraybuffer_expected, + napi_detachable_arraybuffer_expected, + napi_would_deadlock, // unused + napi_no_external_buffers_allowed, + napi_cannot_run_js +} + +export declare const enum napi_property_attributes { + napi_default = 0, + napi_writable = 1 << 0, + napi_enumerable = 1 << 1, + napi_configurable = 1 << 2, + + // Used with napi_define_class to distinguish static properties + // from instance properties. Ignored by napi_define_properties. + napi_static = 1 << 10, + + /// #ifdef NAPI_EXPERIMENTAL + // Default for class methods. + napi_default_method = napi_writable | napi_configurable, + + // Default for object properties, like in JS obj[prop]. + napi_default_jsproperty = napi_writable | napi_enumerable | napi_configurable + /// #endif // NAPI_EXPERIMENTAL +} + +export declare const enum napi_valuetype { + napi_undefined, + napi_null, + napi_boolean, + napi_number, + napi_string, + napi_symbol, + napi_object, + napi_function, + napi_external, + napi_bigint +} + +export declare const enum napi_typedarray_type { + napi_int8_array, + napi_uint8_array, + napi_uint8_clamped_array, + napi_int16_array, + napi_uint16_array, + napi_int32_array, + napi_uint32_array, + napi_float32_array, + napi_float64_array, + napi_bigint64_array, + napi_biguint64_array, + napi_float16_array, +} + +export declare const enum napi_key_collection_mode { + napi_key_include_prototypes, + napi_key_own_only +} + +export declare const enum napi_key_filter { + napi_key_all_properties = 0, + napi_key_writable = 1, + napi_key_enumerable = 1 << 1, + napi_key_configurable = 1 << 2, + napi_key_skip_strings = 1 << 3, + napi_key_skip_symbols = 1 << 4 +} + +export declare const enum napi_key_conversion { + napi_key_keep_numbers, + napi_key_numbers_to_strings +} + +export declare const enum emnapi_memory_view_type { + emnapi_int8_array, + emnapi_uint8_array, + emnapi_uint8_clamped_array, + emnapi_int16_array, + emnapi_uint16_array, + emnapi_int32_array, + emnapi_uint32_array, + emnapi_float32_array, + emnapi_float64_array, + emnapi_bigint64_array, + emnapi_biguint64_array, + emnapi_float16_array, + emnapi_data_view = -1, + emnapi_buffer = -2 +} + +export declare const enum napi_threadsafe_function_call_mode { + napi_tsfn_nonblocking, + napi_tsfn_blocking +} + +export declare const enum napi_threadsafe_function_release_mode { + napi_tsfn_release, + napi_tsfn_abort +} +export declare type CleanupHookCallbackFunction = number | ((arg: number) => void); + +export declare class ConstHandle extends Handle { + constructor(id: number, value: S); + dispose(): void; +} + +export declare class Context { + private _isStopping; + private _canCallIntoJs; + private _suppressDestroy; + envStore: Store; + scopeStore: ScopeStore; + refStore: Store; + deferredStore: Store>; + handleStore: HandleStore; + private readonly refCounter?; + private readonly cleanupQueue; + private readonly _externalMemory; + feature: { + supportReflect: boolean; + supportFinalizer: boolean; + supportWeakSymbol: boolean; + supportBigInt: boolean; + supportNewFunction: boolean; + canSetFunctionName: boolean; + setImmediate: (callback: () => void) => void; + Buffer: BufferCtor | undefined; + MessageChannel: { + new (): MessageChannel; + prototype: MessageChannel; + } | undefined; + }; + constructor(options?: ContextOptions); + /** + * Suppress the destroy on `beforeExit` event in Node.js. + * Call this method if you want to keep the context and + * all associated {@link Env | Env} alive, + * this also means that cleanup hooks will not be called. + * After call this method, you should call + * {@link Context.destroy | `Context.prototype.destroy`} method manually. + */ + suppressDestroy(): void; + getRuntimeVersions(): { + version: string; + NODE_API_SUPPORTED_VERSION_MAX: Version; + NAPI_VERSION_EXPERIMENTAL: Version; + NODE_API_DEFAULT_MODULE_API_VERSION: Version; + }; + createNotSupportWeakRefError(api: string, message: string): NotSupportWeakRefError; + createNotSupportBufferError(api: string, message: string): NotSupportBufferError; + createReference(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership): Reference; + createReferenceWithData(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, data: void_p): Reference; + createReferenceWithFinalizer(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, finalize_callback?: napi_finalize, finalize_data?: void_p, finalize_hint?: void_p): Reference; + createDeferred(value: IDeferrdValue): Deferred; + adjustAmountOfExternalAllocatedMemory(changeInBytes: number | bigint): bigint; + createEnv(filename: string, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never, nodeBinding?: any): Env; + createTrackedFinalizer(envObject: Env, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): TrackedFinalizer; + getCurrentScope(): HandleScope | null; + addToCurrentScope(value: V): Handle; + openScope(envObject?: Env): HandleScope; + closeScope(envObject?: Env, _scope?: HandleScope): void; + ensureHandle(value: S): Handle; + addCleanupHook(envObject: Env, fn: CleanupHookCallbackFunction, arg: number): void; + removeCleanupHook(envObject: Env, fn: CleanupHookCallbackFunction, arg: number): void; + runCleanup(): void; + increaseWaitingRequestCounter(): void; + decreaseWaitingRequestCounter(): void; + setCanCallIntoJs(value: boolean): void; + setStopping(value: boolean): void; + canCallIntoJs(): boolean; + /** + * Destroy the context and call cleanup hooks. + * Associated {@link Env | Env} will be destroyed. + */ + destroy(): void; +} + +export declare interface ContextOptions { + onExternalMemoryChange?: (current: bigint, old: bigint, delta: bigint) => any; +} + +export declare function createContext(options?: ContextOptions): Context; + +export declare class Deferred implements IStoreValue { + static create(ctx: Context, value: IDeferrdValue): Deferred; + id: number; + ctx: Context; + value: IDeferrdValue; + constructor(ctx: Context, value: IDeferrdValue); + resolve(value: T): void; + reject(reason?: any): void; + dispose(): void; +} + +export declare class EmnapiError extends Error { + constructor(message?: string); +} + +export declare abstract class Env implements IStoreValue { + readonly ctx: Context; + moduleApiVersion: number; + makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void; + makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void; + abort: (msg?: string) => never; + id: number; + openHandleScopes: number; + instanceData: TrackedFinalizer | null; + tryCatch: TryCatch; + refs: number; + reflist: RefTracker; + finalizing_reflist: RefTracker; + pendingFinalizers: RefTracker[]; + lastError: { + errorCode: napi_status; + engineErrorCode: number; + engineReserved: Ptr; + }; + inGcFinalizer: boolean; + constructor(ctx: Context, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never); + /** @virtual */ + canCallIntoJs(): boolean; + terminatedOrTerminating(): boolean; + ref(): void; + unref(): void; + ensureHandle(value: S): Handle; + ensureHandleId(value: any): napi_value; + clearLastError(): napi_status; + setLastError(error_code: napi_status, engine_error_code?: uint32_t, engine_reserved?: void_p): napi_status; + getReturnStatus(): napi_status; + callIntoModule(fn: (env: Env) => T, handleException?: (envObject: Env, value: any) => void): T; + /** @virtual */ + abstract callFinalizer(cb: napi_finalize, data: void_p, hint: void_p): void; + invokeFinalizerFromGC(finalizer: RefTracker): void; + checkGCAccess(): void; + /** @virtual */ + enqueueFinalizer(finalizer: RefTracker): void; + /** @virtual */ + dequeueFinalizer(finalizer: RefTracker): void; + /** @virtual */ + deleteMe(): void; + dispose(): void; + private readonly _bindingMap; + initObjectBinding(value: S): IReferenceBinding; + getObjectBinding(value: S): IReferenceBinding; + setInstanceData(data: number, finalize_cb: number, finalize_hint: number): void; + getInstanceData(): number; +} + +/** @public */ +declare interface External_2 extends Record { +} + +/** @public */ +declare const External_2: { + new (value: number | bigint): External_2; + prototype: null; +}; +export { External_2 as External } + +export declare class Finalizer { + envObject: Env; + private _finalizeCallback; + private _finalizeData; + private _finalizeHint; + private _makeDynCall_vppp; + constructor(envObject: Env, _finalizeCallback?: napi_finalize, _finalizeData?: void_p, _finalizeHint?: void_p); + callback(): napi_finalize; + data(): void_p; + hint(): void_p; + resetEnv(): void; + resetFinalizer(): void; + callFinalizer(): void; + dispose(): void; +} + +export declare function getDefaultContext(): Context; + +/** @public */ +export declare function getExternalValue(external: External_2): number | bigint; + +export declare class Handle { + id: number; + value: S; + constructor(id: number, value: S); + data(): void_p; + isNumber(): boolean; + isBigInt(): boolean; + isString(): boolean; + isFunction(): boolean; + isExternal(): boolean; + isObject(): boolean; + isArray(): boolean; + isArrayBuffer(): boolean; + isTypedArray(): boolean; + isBuffer(BufferConstructor?: BufferCtor): boolean; + isDataView(): boolean; + isDate(): boolean; + isPromise(): boolean; + isBoolean(): boolean; + isUndefined(): boolean; + isSymbol(): boolean; + isNull(): boolean; + dispose(): void; +} + +export declare class HandleScope { + handleStore: HandleStore; + id: number; + parent: HandleScope | null; + child: HandleScope | null; + start: number; + end: number; + private _escapeCalled; + callbackInfo: ICallbackInfo; + constructor(handleStore: HandleStore, id: number, parentScope: HandleScope | null, start: number, end?: number); + add(value: V): Handle; + addExternal(data: void_p): Handle; + dispose(): void; + escape(handle: number): Handle | null; + escapeCalled(): boolean; +} + +export declare class HandleStore { + static UNDEFINED: ConstHandle; + static NULL: ConstHandle; + static FALSE: ConstHandle; + static TRUE: ConstHandle; + static GLOBAL: ConstHandle; + static MIN_ID: 6; + private readonly _values; + private _next; + push(value: S): Handle; + erase(start: number, end: number): void; + get(id: Ptr): Handle | undefined; + swap(a: number, b: number): void; + dispose(): void; +} + +export declare interface ICallbackInfo { + thiz: any; + data: void_p; + args: ArrayLike; + fn: Function; +} + +export declare interface IDeferrdValue { + resolve: (value: T) => void; + reject: (reason?: any) => void; +} + +export declare interface IReferenceBinding { + wrapped: number; + tag: Uint32Array | null; +} + +/** @public */ +export declare function isExternal(object: unknown): object is External_2; + +export declare function isReferenceType(v: any): v is object; + +export declare interface IStoreValue { + id: number; + dispose(): void; + [x: string]: any; +} + +export declare const NAPI_VERSION_EXPERIMENTAL = Version.NAPI_VERSION_EXPERIMENTAL; + +export declare const NODE_API_DEFAULT_MODULE_API_VERSION = Version.NODE_API_DEFAULT_MODULE_API_VERSION; + +export declare const NODE_API_SUPPORTED_VERSION_MAX = Version.NODE_API_SUPPORTED_VERSION_MAX; + +export declare const NODE_API_SUPPORTED_VERSION_MIN = Version.NODE_API_SUPPORTED_VERSION_MIN; + +export declare class NodeEnv extends Env { + filename: string; + private readonly nodeBinding?; + destructing: boolean; + finalizationScheduled: boolean; + constructor(ctx: Context, filename: string, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never, nodeBinding?: any); + deleteMe(): void; + canCallIntoJs(): boolean; + triggerFatalException(err: any): void; + callbackIntoModule(enforceUncaughtExceptionPolicy: boolean, fn: (env: Env) => T): T; + callFinalizer(cb: napi_finalize, data: void_p, hint: void_p): void; + callFinalizerInternal(forceUncaught: int, cb: napi_finalize, data: void_p, hint: void_p): void; + enqueueFinalizer(finalizer: RefTracker): void; + drainFinalizerQueue(): void; +} + +export declare class NotSupportBufferError extends EmnapiError { + constructor(api: string, message: string); +} + +export declare class NotSupportWeakRefError extends EmnapiError { + constructor(api: string, message: string); +} + +export declare class Persistent { + private _ref; + private _param; + private _callback; + private static readonly _registry; + constructor(value: T); + setWeak

(param: P, callback: (param: P) => void): void; + clearWeak(): void; + reset(): void; + isEmpty(): boolean; + deref(): T | undefined; +} + +export declare class Reference extends RefTracker implements IStoreValue { + private static weakCallback; + id: number; + envObject: Env; + private readonly canBeWeak; + private _refcount; + private readonly _ownership; + persistent: Persistent; + static create(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, _unused1?: void_p, _unused2?: void_p, _unused3?: void_p): Reference; + protected constructor(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership); + ref(): number; + unref(): number; + get(envObject?: Env): napi_value; + /** @virtual */ + resetFinalizer(): void; + /** @virtual */ + data(): void_p; + refcount(): number; + ownership(): ReferenceOwnership; + /** @virtual */ + protected callUserFinalizer(): void; + /** @virtual */ + protected invokeFinalizerFromGC(): void; + private _setWeak; + finalize(): void; + dispose(): void; +} + +export declare enum ReferenceOwnership { + kRuntime = 0, + kUserland = 1 +} + +export declare class ReferenceWithData extends Reference { + private readonly _data; + static create(envObject: Env, value: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, data: void_p): ReferenceWithData; + private constructor(); + data(): void_p; +} + +export declare class ReferenceWithFinalizer extends Reference { + private _finalizer; + static create(envObject: Env, value: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): ReferenceWithFinalizer; + private constructor(); + resetFinalizer(): void; + data(): void_p; + protected callUserFinalizer(): void; + protected invokeFinalizerFromGC(): void; + dispose(): void; +} + +export declare class RefTracker { + /** @virtual */ + dispose(): void; + /** @virtual */ + finalize(): void; + private _next; + private _prev; + link(list: RefTracker): void; + unlink(): void; + static finalizeAll(list: RefTracker): void; +} + +export declare class ScopeStore { + private readonly _rootScope; + currentScope: HandleScope; + private readonly _values; + constructor(); + get(id: number): HandleScope | undefined; + openScope(handleStore: HandleStore): HandleScope; + closeScope(): void; + dispose(): void; +} + +export declare class Store { + protected _values: Array; + private _freeList; + private _size; + constructor(); + add(value: V): void; + get(id: Ptr): V | undefined; + has(id: Ptr): boolean; + remove(id: Ptr): void; + dispose(): void; +} + +export declare class TrackedFinalizer extends RefTracker { + private _finalizer; + static create(envObject: Env, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): TrackedFinalizer; + private constructor(); + data(): void_p; + dispose(): void; + finalize(): void; +} + +export declare class TryCatch { + private _exception; + private _caught; + isEmpty(): boolean; + hasCaught(): boolean; + exception(): any; + setError(err: any): void; + reset(): void; + extractException(): any; +} + +export declare const version: string; + +export { } diff --git a/node_modules/@emnapi/runtime/dist/emnapi.d.ts b/node_modules/@emnapi/runtime/dist/emnapi.d.ts new file mode 100644 index 0000000..cf4653b --- /dev/null +++ b/node_modules/@emnapi/runtime/dist/emnapi.d.ts @@ -0,0 +1,673 @@ +export declare type Ptr = number | bigint + +export declare interface IBuffer extends Uint8Array {} +export declare interface BufferCtor { + readonly prototype: IBuffer + /** @deprecated */ + new (...args: any[]): IBuffer + from: { + (buffer: ArrayBufferLike): IBuffer + (buffer: ArrayBufferLike, byteOffset: number, length: number): IBuffer + } + alloc: (size: number) => IBuffer + isBuffer: (obj: unknown) => obj is IBuffer +} + +export declare const enum GlobalHandle { + UNDEFINED = 1, + NULL, + FALSE, + TRUE, + GLOBAL +} + +export declare const enum Version { + NODE_API_SUPPORTED_VERSION_MIN = 1, + NODE_API_DEFAULT_MODULE_API_VERSION = 8, + NODE_API_SUPPORTED_VERSION_MAX = 10, + NAPI_VERSION_EXPERIMENTAL = 2147483647 // INT_MAX +} +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export declare type Pointer = number +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export declare type PointerPointer = number +export declare type FunctionPointer any> = Pointer +export declare type Const = T + +export declare type void_p = Pointer +export declare type void_pp = Pointer +export declare type bool = number +export declare type char = number +export declare type char_p = Pointer +export declare type unsigned_char = number +export declare type const_char = Const +export declare type const_char_p = Pointer +export declare type char16_t_p = number +export declare type const_char16_t_p = number + +export declare type short = number +export declare type unsigned_short = number +export declare type int = number +export declare type unsigned_int = number +export declare type long = number +export declare type unsigned_long = number +export declare type long_long = bigint +export declare type unsigned_long_long = bigint +export declare type float = number +export declare type double = number +export declare type long_double = number +export declare type size_t = number + +export declare type int8_t = number +export declare type uint8_t = number +export declare type int16_t = number +export declare type uint16_t = number +export declare type int32_t = number +export declare type uint32_t = number +export declare type int64_t = bigint +export declare type uint64_t = bigint +export declare type napi_env = Pointer + +export declare type napi_value = Pointer +export declare type napi_ref = Pointer +export declare type napi_deferred = Pointer +export declare type napi_handle_scope = Pointer +export declare type napi_escapable_handle_scope = Pointer + +export declare type napi_addon_register_func = FunctionPointer<(env: napi_env, exports: napi_value) => napi_value> + +export declare type napi_callback_info = Pointer +export declare type napi_callback = FunctionPointer<(env: napi_env, info: napi_callback_info) => napi_value> + +export declare interface napi_extended_error_info { + error_message: const_char_p + engine_reserved: void_p + engine_error_code: uint32_t + error_code: napi_status +} + +export declare interface napi_property_descriptor { + // One of utf8name or name should be NULL. + utf8name: const_char_p + name: napi_value + + method: napi_callback + getter: napi_callback + setter: napi_callback + value: napi_value + /* napi_property_attributes */ + attributes: number + data: void_p +} + +export declare type napi_finalize = FunctionPointer<( + env: napi_env, + finalize_data: void_p, + finalize_hint: void_p +) => void> + +export declare interface node_module { + nm_version: int32_t + nm_flags: uint32_t + nm_filename: Pointer + nm_register_func: napi_addon_register_func + nm_modname: Pointer + nm_priv: Pointer + reserved: PointerPointer +} + +export declare interface napi_node_version { + major: uint32_t + minor: uint32_t + patch: uint32_t + release: const_char_p +} + +export declare interface emnapi_emscripten_version { + major: uint32_t + minor: uint32_t + patch: uint32_t +} + +export declare const enum napi_status { + napi_ok, + napi_invalid_arg, + napi_object_expected, + napi_string_expected, + napi_name_expected, + napi_function_expected, + napi_number_expected, + napi_boolean_expected, + napi_array_expected, + napi_generic_failure, + napi_pending_exception, + napi_cancelled, + napi_escape_called_twice, + napi_handle_scope_mismatch, + napi_callback_scope_mismatch, + napi_queue_full, + napi_closing, + napi_bigint_expected, + napi_date_expected, + napi_arraybuffer_expected, + napi_detachable_arraybuffer_expected, + napi_would_deadlock, // unused + napi_no_external_buffers_allowed, + napi_cannot_run_js +} + +export declare const enum napi_property_attributes { + napi_default = 0, + napi_writable = 1 << 0, + napi_enumerable = 1 << 1, + napi_configurable = 1 << 2, + + // Used with napi_define_class to distinguish static properties + // from instance properties. Ignored by napi_define_properties. + napi_static = 1 << 10, + + /// #ifdef NAPI_EXPERIMENTAL + // Default for class methods. + napi_default_method = napi_writable | napi_configurable, + + // Default for object properties, like in JS obj[prop]. + napi_default_jsproperty = napi_writable | napi_enumerable | napi_configurable + /// #endif // NAPI_EXPERIMENTAL +} + +export declare const enum napi_valuetype { + napi_undefined, + napi_null, + napi_boolean, + napi_number, + napi_string, + napi_symbol, + napi_object, + napi_function, + napi_external, + napi_bigint +} + +export declare const enum napi_typedarray_type { + napi_int8_array, + napi_uint8_array, + napi_uint8_clamped_array, + napi_int16_array, + napi_uint16_array, + napi_int32_array, + napi_uint32_array, + napi_float32_array, + napi_float64_array, + napi_bigint64_array, + napi_biguint64_array, + napi_float16_array, +} + +export declare const enum napi_key_collection_mode { + napi_key_include_prototypes, + napi_key_own_only +} + +export declare const enum napi_key_filter { + napi_key_all_properties = 0, + napi_key_writable = 1, + napi_key_enumerable = 1 << 1, + napi_key_configurable = 1 << 2, + napi_key_skip_strings = 1 << 3, + napi_key_skip_symbols = 1 << 4 +} + +export declare const enum napi_key_conversion { + napi_key_keep_numbers, + napi_key_numbers_to_strings +} + +export declare const enum emnapi_memory_view_type { + emnapi_int8_array, + emnapi_uint8_array, + emnapi_uint8_clamped_array, + emnapi_int16_array, + emnapi_uint16_array, + emnapi_int32_array, + emnapi_uint32_array, + emnapi_float32_array, + emnapi_float64_array, + emnapi_bigint64_array, + emnapi_biguint64_array, + emnapi_float16_array, + emnapi_data_view = -1, + emnapi_buffer = -2 +} + +export declare const enum napi_threadsafe_function_call_mode { + napi_tsfn_nonblocking, + napi_tsfn_blocking +} + +export declare const enum napi_threadsafe_function_release_mode { + napi_tsfn_release, + napi_tsfn_abort +} +export declare type CleanupHookCallbackFunction = number | ((arg: number) => void); + +export declare class ConstHandle extends Handle { + constructor(id: number, value: S); + dispose(): void; +} + +export declare class Context { + private _isStopping; + private _canCallIntoJs; + private _suppressDestroy; + envStore: Store; + scopeStore: ScopeStore; + refStore: Store; + deferredStore: Store>; + handleStore: HandleStore; + private readonly refCounter?; + private readonly cleanupQueue; + private readonly _externalMemory; + feature: { + supportReflect: boolean; + supportFinalizer: boolean; + supportWeakSymbol: boolean; + supportBigInt: boolean; + supportNewFunction: boolean; + canSetFunctionName: boolean; + setImmediate: (callback: () => void) => void; + Buffer: BufferCtor | undefined; + MessageChannel: { + new (): MessageChannel; + prototype: MessageChannel; + } | undefined; + }; + constructor(options?: ContextOptions); + /** + * Suppress the destroy on `beforeExit` event in Node.js. + * Call this method if you want to keep the context and + * all associated {@link Env | Env} alive, + * this also means that cleanup hooks will not be called. + * After call this method, you should call + * {@link Context.destroy | `Context.prototype.destroy`} method manually. + */ + suppressDestroy(): void; + getRuntimeVersions(): { + version: string; + NODE_API_SUPPORTED_VERSION_MAX: Version; + NAPI_VERSION_EXPERIMENTAL: Version; + NODE_API_DEFAULT_MODULE_API_VERSION: Version; + }; + createNotSupportWeakRefError(api: string, message: string): NotSupportWeakRefError; + createNotSupportBufferError(api: string, message: string): NotSupportBufferError; + createReference(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership): Reference; + createReferenceWithData(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, data: void_p): Reference; + createReferenceWithFinalizer(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, finalize_callback?: napi_finalize, finalize_data?: void_p, finalize_hint?: void_p): Reference; + createDeferred(value: IDeferrdValue): Deferred; + adjustAmountOfExternalAllocatedMemory(changeInBytes: number | bigint): bigint; + createEnv(filename: string, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never, nodeBinding?: any): Env; + createTrackedFinalizer(envObject: Env, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): TrackedFinalizer; + getCurrentScope(): HandleScope | null; + addToCurrentScope(value: V): Handle; + openScope(envObject?: Env): HandleScope; + closeScope(envObject?: Env, _scope?: HandleScope): void; + ensureHandle(value: S): Handle; + addCleanupHook(envObject: Env, fn: CleanupHookCallbackFunction, arg: number): void; + removeCleanupHook(envObject: Env, fn: CleanupHookCallbackFunction, arg: number): void; + runCleanup(): void; + increaseWaitingRequestCounter(): void; + decreaseWaitingRequestCounter(): void; + setCanCallIntoJs(value: boolean): void; + setStopping(value: boolean): void; + canCallIntoJs(): boolean; + /** + * Destroy the context and call cleanup hooks. + * Associated {@link Env | Env} will be destroyed. + */ + destroy(): void; +} + +export declare interface ContextOptions { + onExternalMemoryChange?: (current: bigint, old: bigint, delta: bigint) => any; +} + +export declare function createContext(options?: ContextOptions): Context; + +export declare class Deferred implements IStoreValue { + static create(ctx: Context, value: IDeferrdValue): Deferred; + id: number; + ctx: Context; + value: IDeferrdValue; + constructor(ctx: Context, value: IDeferrdValue); + resolve(value: T): void; + reject(reason?: any): void; + dispose(): void; +} + +export declare class EmnapiError extends Error { + constructor(message?: string); +} + +export declare abstract class Env implements IStoreValue { + readonly ctx: Context; + moduleApiVersion: number; + makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void; + makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void; + abort: (msg?: string) => never; + id: number; + openHandleScopes: number; + instanceData: TrackedFinalizer | null; + tryCatch: TryCatch; + refs: number; + reflist: RefTracker; + finalizing_reflist: RefTracker; + pendingFinalizers: RefTracker[]; + lastError: { + errorCode: napi_status; + engineErrorCode: number; + engineReserved: Ptr; + }; + inGcFinalizer: boolean; + constructor(ctx: Context, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never); + /** @virtual */ + canCallIntoJs(): boolean; + terminatedOrTerminating(): boolean; + ref(): void; + unref(): void; + ensureHandle(value: S): Handle; + ensureHandleId(value: any): napi_value; + clearLastError(): napi_status; + setLastError(error_code: napi_status, engine_error_code?: uint32_t, engine_reserved?: void_p): napi_status; + getReturnStatus(): napi_status; + callIntoModule(fn: (env: Env) => T, handleException?: (envObject: Env, value: any) => void): T; + /** @virtual */ + abstract callFinalizer(cb: napi_finalize, data: void_p, hint: void_p): void; + invokeFinalizerFromGC(finalizer: RefTracker): void; + checkGCAccess(): void; + /** @virtual */ + enqueueFinalizer(finalizer: RefTracker): void; + /** @virtual */ + dequeueFinalizer(finalizer: RefTracker): void; + /** @virtual */ + deleteMe(): void; + dispose(): void; + private readonly _bindingMap; + initObjectBinding(value: S): IReferenceBinding; + getObjectBinding(value: S): IReferenceBinding; + setInstanceData(data: number, finalize_cb: number, finalize_hint: number): void; + getInstanceData(): number; +} + +/** @public */ +declare interface External_2 extends Record { +} + +/** @public */ +declare const External_2: { + new (value: number | bigint): External_2; + prototype: null; +}; +export { External_2 as External } + +export declare class Finalizer { + envObject: Env; + private _finalizeCallback; + private _finalizeData; + private _finalizeHint; + private _makeDynCall_vppp; + constructor(envObject: Env, _finalizeCallback?: napi_finalize, _finalizeData?: void_p, _finalizeHint?: void_p); + callback(): napi_finalize; + data(): void_p; + hint(): void_p; + resetEnv(): void; + resetFinalizer(): void; + callFinalizer(): void; + dispose(): void; +} + +export declare function getDefaultContext(): Context; + +/** @public */ +export declare function getExternalValue(external: External_2): number | bigint; + +export declare class Handle { + id: number; + value: S; + constructor(id: number, value: S); + data(): void_p; + isNumber(): boolean; + isBigInt(): boolean; + isString(): boolean; + isFunction(): boolean; + isExternal(): boolean; + isObject(): boolean; + isArray(): boolean; + isArrayBuffer(): boolean; + isTypedArray(): boolean; + isBuffer(BufferConstructor?: BufferCtor): boolean; + isDataView(): boolean; + isDate(): boolean; + isPromise(): boolean; + isBoolean(): boolean; + isUndefined(): boolean; + isSymbol(): boolean; + isNull(): boolean; + dispose(): void; +} + +export declare class HandleScope { + handleStore: HandleStore; + id: number; + parent: HandleScope | null; + child: HandleScope | null; + start: number; + end: number; + private _escapeCalled; + callbackInfo: ICallbackInfo; + constructor(handleStore: HandleStore, id: number, parentScope: HandleScope | null, start: number, end?: number); + add(value: V): Handle; + addExternal(data: void_p): Handle; + dispose(): void; + escape(handle: number): Handle | null; + escapeCalled(): boolean; +} + +export declare class HandleStore { + static UNDEFINED: ConstHandle; + static NULL: ConstHandle; + static FALSE: ConstHandle; + static TRUE: ConstHandle; + static GLOBAL: ConstHandle; + static MIN_ID: 6; + private readonly _values; + private _next; + push(value: S): Handle; + erase(start: number, end: number): void; + get(id: Ptr): Handle | undefined; + swap(a: number, b: number): void; + dispose(): void; +} + +export declare interface ICallbackInfo { + thiz: any; + data: void_p; + args: ArrayLike; + fn: Function; +} + +export declare interface IDeferrdValue { + resolve: (value: T) => void; + reject: (reason?: any) => void; +} + +export declare interface IReferenceBinding { + wrapped: number; + tag: Uint32Array | null; +} + +/** @public */ +export declare function isExternal(object: unknown): object is External_2; + +export declare function isReferenceType(v: any): v is object; + +export declare interface IStoreValue { + id: number; + dispose(): void; + [x: string]: any; +} + +export declare const NAPI_VERSION_EXPERIMENTAL = Version.NAPI_VERSION_EXPERIMENTAL; + +export declare const NODE_API_DEFAULT_MODULE_API_VERSION = Version.NODE_API_DEFAULT_MODULE_API_VERSION; + +export declare const NODE_API_SUPPORTED_VERSION_MAX = Version.NODE_API_SUPPORTED_VERSION_MAX; + +export declare const NODE_API_SUPPORTED_VERSION_MIN = Version.NODE_API_SUPPORTED_VERSION_MIN; + +export declare class NodeEnv extends Env { + filename: string; + private readonly nodeBinding?; + destructing: boolean; + finalizationScheduled: boolean; + constructor(ctx: Context, filename: string, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never, nodeBinding?: any); + deleteMe(): void; + canCallIntoJs(): boolean; + triggerFatalException(err: any): void; + callbackIntoModule(enforceUncaughtExceptionPolicy: boolean, fn: (env: Env) => T): T; + callFinalizer(cb: napi_finalize, data: void_p, hint: void_p): void; + callFinalizerInternal(forceUncaught: int, cb: napi_finalize, data: void_p, hint: void_p): void; + enqueueFinalizer(finalizer: RefTracker): void; + drainFinalizerQueue(): void; +} + +export declare class NotSupportBufferError extends EmnapiError { + constructor(api: string, message: string); +} + +export declare class NotSupportWeakRefError extends EmnapiError { + constructor(api: string, message: string); +} + +export declare class Persistent { + private _ref; + private _param; + private _callback; + private static readonly _registry; + constructor(value: T); + setWeak

(param: P, callback: (param: P) => void): void; + clearWeak(): void; + reset(): void; + isEmpty(): boolean; + deref(): T | undefined; +} + +export declare class Reference extends RefTracker implements IStoreValue { + private static weakCallback; + id: number; + envObject: Env; + private readonly canBeWeak; + private _refcount; + private readonly _ownership; + persistent: Persistent; + static create(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, _unused1?: void_p, _unused2?: void_p, _unused3?: void_p): Reference; + protected constructor(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership); + ref(): number; + unref(): number; + get(envObject?: Env): napi_value; + /** @virtual */ + resetFinalizer(): void; + /** @virtual */ + data(): void_p; + refcount(): number; + ownership(): ReferenceOwnership; + /** @virtual */ + protected callUserFinalizer(): void; + /** @virtual */ + protected invokeFinalizerFromGC(): void; + private _setWeak; + finalize(): void; + dispose(): void; +} + +export declare enum ReferenceOwnership { + kRuntime = 0, + kUserland = 1 +} + +export declare class ReferenceWithData extends Reference { + private readonly _data; + static create(envObject: Env, value: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, data: void_p): ReferenceWithData; + private constructor(); + data(): void_p; +} + +export declare class ReferenceWithFinalizer extends Reference { + private _finalizer; + static create(envObject: Env, value: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): ReferenceWithFinalizer; + private constructor(); + resetFinalizer(): void; + data(): void_p; + protected callUserFinalizer(): void; + protected invokeFinalizerFromGC(): void; + dispose(): void; +} + +export declare class RefTracker { + /** @virtual */ + dispose(): void; + /** @virtual */ + finalize(): void; + private _next; + private _prev; + link(list: RefTracker): void; + unlink(): void; + static finalizeAll(list: RefTracker): void; +} + +export declare class ScopeStore { + private readonly _rootScope; + currentScope: HandleScope; + private readonly _values; + constructor(); + get(id: number): HandleScope | undefined; + openScope(handleStore: HandleStore): HandleScope; + closeScope(): void; + dispose(): void; +} + +export declare class Store { + protected _values: Array; + private _freeList; + private _size; + constructor(); + add(value: V): void; + get(id: Ptr): V | undefined; + has(id: Ptr): boolean; + remove(id: Ptr): void; + dispose(): void; +} + +export declare class TrackedFinalizer extends RefTracker { + private _finalizer; + static create(envObject: Env, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): TrackedFinalizer; + private constructor(); + data(): void_p; + dispose(): void; + finalize(): void; +} + +export declare class TryCatch { + private _exception; + private _caught; + isEmpty(): boolean; + hasCaught(): boolean; + exception(): any; + setError(err: any): void; + reset(): void; + extractException(): any; +} + +export declare const version: string; + +export { } + +export as namespace emnapi; diff --git a/node_modules/@emnapi/runtime/dist/emnapi.esm-bundler.js b/node_modules/@emnapi/runtime/dist/emnapi.esm-bundler.js new file mode 100644 index 0000000..bed71f4 --- /dev/null +++ b/node_modules/@emnapi/runtime/dist/emnapi.esm-bundler.js @@ -0,0 +1,1457 @@ +import { __extends } from 'tslib'; + +var externalValue = new WeakMap(); +/** @public */ +function isExternal(object) { + return externalValue.has(object); +} +/** @public */ // eslint-disable-next-line @typescript-eslint/no-redeclare +var External = (function () { + function External(value) { + Object.setPrototypeOf(this, null); + externalValue.set(this, value); + } + External.prototype = null; + return External; +})(); +/** @public */ +function getExternalValue(external) { + if (!isExternal(external)) { + throw new TypeError('not external'); + } + return externalValue.get(external); +} + +var supportNewFunction = /*#__PURE__*/ (function () { + var f; + try { + f = new Function(); + } + catch (_) { + return false; + } + return typeof f === 'function'; +})(); +var _global = /*#__PURE__*/ (function () { + if (typeof globalThis !== 'undefined') + return globalThis; + var g = (function () { return this; })(); + if (!g && supportNewFunction) { + try { + g = new Function('return this')(); + } + catch (_) { } + } + if (!g) { + if (typeof __webpack_public_path__ === 'undefined') { + if (typeof global !== 'undefined') + return global; + } + if (typeof window !== 'undefined') + return window; + if (typeof self !== 'undefined') + return self; + } + return g; +})(); +var TryCatch = /*#__PURE__*/ (function () { + function TryCatch() { + this._exception = undefined; + this._caught = false; + } + TryCatch.prototype.isEmpty = function () { + return !this._caught; + }; + TryCatch.prototype.hasCaught = function () { + return this._caught; + }; + TryCatch.prototype.exception = function () { + return this._exception; + }; + TryCatch.prototype.setError = function (err) { + this._caught = true; + this._exception = err; + }; + TryCatch.prototype.reset = function () { + this._caught = false; + this._exception = undefined; + }; + TryCatch.prototype.extractException = function () { + var e = this._exception; + this.reset(); + return e; + }; + return TryCatch; +}()); +var canSetFunctionName = /*#__PURE__*/ (function () { + var _a; + try { + return Boolean((_a = Object.getOwnPropertyDescriptor(Function.prototype, 'name')) === null || _a === void 0 ? void 0 : _a.configurable); + } + catch (_) { + return false; + } +})(); +var supportReflect = typeof Reflect === 'object'; +var supportFinalizer = (typeof FinalizationRegistry !== 'undefined') && (typeof WeakRef !== 'undefined'); +var supportWeakSymbol = /*#__PURE__*/ (function () { + try { + // eslint-disable-next-line symbol-description + var sym = Symbol(); + // eslint-disable-next-line no-new + new WeakRef(sym); + new WeakMap().set(sym, undefined); + } + catch (_) { + return false; + } + return true; +})(); +var supportBigInt = typeof BigInt !== 'undefined'; +function isReferenceType(v) { + return (typeof v === 'object' && v !== null) || typeof v === 'function'; +} +var _require = /*#__PURE__*/ (function () { + var nativeRequire; + if (typeof __webpack_public_path__ !== 'undefined') { + nativeRequire = (function () { + return typeof __non_webpack_require__ !== 'undefined' ? __non_webpack_require__ : undefined; + })(); + } + else { + nativeRequire = (function () { + return typeof __webpack_public_path__ !== 'undefined' ? (typeof __non_webpack_require__ !== 'undefined' ? __non_webpack_require__ : undefined) : (typeof require !== 'undefined' ? require : undefined); + })(); + } + return nativeRequire; +})(); +var _MessageChannel = typeof MessageChannel === 'function' + ? MessageChannel + : /*#__PURE__*/ (function () { + try { + return _require('worker_threads').MessageChannel; + } + catch (_) { } + return undefined; + })(); +var _setImmediate = typeof setImmediate === 'function' + ? setImmediate.bind(_global) + : function (callback) { + if (typeof callback !== 'function') { + throw new TypeError('The "callback" argument must be of type function'); + } + if (_MessageChannel) { + var channel_1 = new _MessageChannel(); + channel_1.port1.onmessage = function () { + channel_1.port1.onmessage = null; + channel_1 = undefined; + callback(); + }; + channel_1.port2.postMessage(null); + } + else { + setTimeout(callback, 0); + } + }; +var _Buffer = typeof Buffer === 'function' + ? Buffer + : /*#__PURE__*/ (function () { + try { + return _require('buffer').Buffer; + } + catch (_) { } + return undefined; + })(); +var version = "1.11.3"; +var NODE_API_SUPPORTED_VERSION_MIN = 1 /* Version.NODE_API_SUPPORTED_VERSION_MIN */; +var NODE_API_SUPPORTED_VERSION_MAX = 10 /* Version.NODE_API_SUPPORTED_VERSION_MAX */; +var NAPI_VERSION_EXPERIMENTAL = 2147483647 /* Version.NAPI_VERSION_EXPERIMENTAL */; +var NODE_API_DEFAULT_MODULE_API_VERSION = 8 /* Version.NODE_API_DEFAULT_MODULE_API_VERSION */; + +var Handle = /*#__PURE__*/ (function () { + function Handle(id, value) { + this.id = id; + this.value = value; + } + Handle.prototype.data = function () { + return getExternalValue(this.value); + }; + Handle.prototype.isNumber = function () { + return typeof this.value === 'number'; + }; + Handle.prototype.isBigInt = function () { + return typeof this.value === 'bigint'; + }; + Handle.prototype.isString = function () { + return typeof this.value === 'string'; + }; + Handle.prototype.isFunction = function () { + return typeof this.value === 'function'; + }; + Handle.prototype.isExternal = function () { + return isExternal(this.value); + }; + Handle.prototype.isObject = function () { + return typeof this.value === 'object' && this.value !== null; + }; + Handle.prototype.isArray = function () { + return Array.isArray(this.value); + }; + Handle.prototype.isArrayBuffer = function () { + return (this.value instanceof ArrayBuffer); + }; + Handle.prototype.isTypedArray = function () { + return (ArrayBuffer.isView(this.value)) && !(this.value instanceof DataView); + }; + Handle.prototype.isBuffer = function (BufferConstructor) { + if (ArrayBuffer.isView(this.value)) + return true; + BufferConstructor !== null && BufferConstructor !== void 0 ? BufferConstructor : (BufferConstructor = _Buffer); + return typeof BufferConstructor === 'function' && BufferConstructor.isBuffer(this.value); + }; + Handle.prototype.isDataView = function () { + return (this.value instanceof DataView); + }; + Handle.prototype.isDate = function () { + return (this.value instanceof Date); + }; + Handle.prototype.isPromise = function () { + return (this.value instanceof Promise); + }; + Handle.prototype.isBoolean = function () { + return typeof this.value === 'boolean'; + }; + Handle.prototype.isUndefined = function () { + return this.value === undefined; + }; + Handle.prototype.isSymbol = function () { + return typeof this.value === 'symbol'; + }; + Handle.prototype.isNull = function () { + return this.value === null; + }; + Handle.prototype.dispose = function () { + this.value = undefined; + }; + return Handle; +}()); +var ConstHandle = /*#__PURE__*/ (function (_super) { + __extends(ConstHandle, _super); + function ConstHandle(id, value) { + return _super.call(this, id, value) || this; + } + ConstHandle.prototype.dispose = function () { }; + return ConstHandle; +}(Handle)); +var HandleStore = /*#__PURE__*/ (function () { + function HandleStore() { + this._values = [ + undefined, + HandleStore.UNDEFINED, + HandleStore.NULL, + HandleStore.FALSE, + HandleStore.TRUE, + HandleStore.GLOBAL + ]; + this._next = HandleStore.MIN_ID; + } + HandleStore.prototype.push = function (value) { + var h; + var next = this._next; + var values = this._values; + if (next < values.length) { + h = values[next]; + h.value = value; + } + else { + h = new Handle(next, value); + values[next] = h; + } + this._next++; + return h; + }; + HandleStore.prototype.erase = function (start, end) { + this._next = start; + var values = this._values; + for (var i = start; i < end; ++i) { + values[i].dispose(); + } + }; + HandleStore.prototype.get = function (id) { + return this._values[id]; + }; + HandleStore.prototype.swap = function (a, b) { + var values = this._values; + var h = values[a]; + values[a] = values[b]; + values[a].id = Number(a); + values[b] = h; + h.id = Number(b); + }; + HandleStore.prototype.dispose = function () { + this._values.length = HandleStore.MIN_ID; + this._next = HandleStore.MIN_ID; + }; + HandleStore.UNDEFINED = new ConstHandle(1 /* GlobalHandle.UNDEFINED */, undefined); + HandleStore.NULL = new ConstHandle(2 /* GlobalHandle.NULL */, null); + HandleStore.FALSE = new ConstHandle(3 /* GlobalHandle.FALSE */, false); + HandleStore.TRUE = new ConstHandle(4 /* GlobalHandle.TRUE */, true); + HandleStore.GLOBAL = new ConstHandle(5 /* GlobalHandle.GLOBAL */, _global); + HandleStore.MIN_ID = 6; + return HandleStore; +}()); + +var HandleScope = /*#__PURE__*/ (function () { + function HandleScope(handleStore, id, parentScope, start, end) { + if (end === void 0) { end = start; } + this.handleStore = handleStore; + this.id = id; + this.parent = parentScope; + this.child = null; + if (parentScope !== null) + parentScope.child = this; + this.start = start; + this.end = end; + this._escapeCalled = false; + this.callbackInfo = { + thiz: undefined, + data: 0, + args: undefined, + fn: undefined + }; + } + HandleScope.prototype.add = function (value) { + var h = this.handleStore.push(value); + this.end++; + return h; + }; + HandleScope.prototype.addExternal = function (data) { + return this.add(new External(data)); + }; + HandleScope.prototype.dispose = function () { + if (this._escapeCalled) + this._escapeCalled = false; + if (this.start === this.end) + return; + this.handleStore.erase(this.start, this.end); + }; + HandleScope.prototype.escape = function (handle) { + if (this._escapeCalled) + return null; + this._escapeCalled = true; + if (handle < this.start || handle >= this.end) { + return null; + } + this.handleStore.swap(handle, this.start); + var h = this.handleStore.get(this.start); + this.start++; + this.parent.end++; + return h; + }; + HandleScope.prototype.escapeCalled = function () { + return this._escapeCalled; + }; + return HandleScope; +}()); + +var ScopeStore = /*#__PURE__*/ (function () { + function ScopeStore() { + this._rootScope = new HandleScope(null, 0, null, 1, HandleStore.MIN_ID); + this.currentScope = this._rootScope; + this._values = [undefined]; + } + ScopeStore.prototype.get = function (id) { + return this._values[id]; + }; + ScopeStore.prototype.openScope = function (handleStore) { + var currentScope = this.currentScope; + var scope = currentScope.child; + if (scope !== null) { + scope.start = scope.end = currentScope.end; + } + else { + var id = currentScope.id + 1; + scope = new HandleScope(handleStore, id, currentScope, currentScope.end); + this._values[id] = scope; + } + this.currentScope = scope; + return scope; + }; + ScopeStore.prototype.closeScope = function () { + var scope = this.currentScope; + this.currentScope = scope.parent; + scope.dispose(); + }; + ScopeStore.prototype.dispose = function () { + this.currentScope = this._rootScope; + this._values.length = 1; + }; + return ScopeStore; +}()); + +var RefTracker = /*#__PURE__*/ (function () { + function RefTracker() { + this._next = null; + this._prev = null; + } + /** @virtual */ + RefTracker.prototype.dispose = function () { }; + /** @virtual */ + RefTracker.prototype.finalize = function () { }; + RefTracker.prototype.link = function (list) { + this._prev = list; + this._next = list._next; + if (this._next !== null) { + this._next._prev = this; + } + list._next = this; + }; + RefTracker.prototype.unlink = function () { + if (this._prev !== null) { + this._prev._next = this._next; + } + if (this._next !== null) { + this._next._prev = this._prev; + } + this._prev = null; + this._next = null; + }; + RefTracker.finalizeAll = function (list) { + while (list._next !== null) { + list._next.finalize(); + } + }; + return RefTracker; +}()); + +var Finalizer = /*#__PURE__*/ (function () { + function Finalizer(envObject, _finalizeCallback, _finalizeData, _finalizeHint) { + if (_finalizeCallback === void 0) { _finalizeCallback = 0; } + if (_finalizeData === void 0) { _finalizeData = 0; } + if (_finalizeHint === void 0) { _finalizeHint = 0; } + this.envObject = envObject; + this._finalizeCallback = _finalizeCallback; + this._finalizeData = _finalizeData; + this._finalizeHint = _finalizeHint; + this._makeDynCall_vppp = envObject.makeDynCall_vppp; + } + Finalizer.prototype.callback = function () { return this._finalizeCallback; }; + Finalizer.prototype.data = function () { return this._finalizeData; }; + Finalizer.prototype.hint = function () { return this._finalizeHint; }; + Finalizer.prototype.resetEnv = function () { + this.envObject = undefined; + }; + Finalizer.prototype.resetFinalizer = function () { + this._finalizeCallback = 0; + this._finalizeData = 0; + this._finalizeHint = 0; + }; + Finalizer.prototype.callFinalizer = function () { + var finalize_callback = this._finalizeCallback; + var finalize_data = this._finalizeData; + var finalize_hint = this._finalizeHint; + this.resetFinalizer(); + if (!finalize_callback) + return; + var fini = Number(finalize_callback); + if (!this.envObject) { + this._makeDynCall_vppp(fini)(0, finalize_data, finalize_hint); + } + else { + this.envObject.callFinalizer(fini, finalize_data, finalize_hint); + } + }; + Finalizer.prototype.dispose = function () { + this.envObject = undefined; + this._makeDynCall_vppp = undefined; + }; + return Finalizer; +}()); + +var TrackedFinalizer = /*#__PURE__*/ (function (_super) { + __extends(TrackedFinalizer, _super); + function TrackedFinalizer(envObject, finalize_callback, finalize_data, finalize_hint) { + var _this = _super.call(this) || this; + _this._finalizer = new Finalizer(envObject, finalize_callback, finalize_data, finalize_hint); + return _this; + } + TrackedFinalizer.create = function (envObject, finalize_callback, finalize_data, finalize_hint) { + var finalizer = new TrackedFinalizer(envObject, finalize_callback, finalize_data, finalize_hint); + finalizer.link(envObject.finalizing_reflist); + return finalizer; + }; + TrackedFinalizer.prototype.data = function () { + return this._finalizer.data(); + }; + TrackedFinalizer.prototype.dispose = function () { + if (!this._finalizer) + return; + this.unlink(); + this._finalizer.envObject.dequeueFinalizer(this); + this._finalizer.dispose(); + this._finalizer = undefined; + _super.prototype.dispose.call(this); + }; + TrackedFinalizer.prototype.finalize = function () { + this.unlink(); + var error; + var caught = false; + try { + this._finalizer.callFinalizer(); + } + catch (err) { + caught = true; + error = err; + } + this.dispose(); + if (caught) { + throw error; + } + }; + return TrackedFinalizer; +}(RefTracker)); + +function throwNodeApiVersionError(moduleName, moduleApiVersion) { + var errorMessage = "".concat(moduleName, " requires Node-API version ").concat(moduleApiVersion, ", but this version of Node.js only supports version ").concat(NODE_API_SUPPORTED_VERSION_MAX, " add-ons."); + throw new Error(errorMessage); +} +function handleThrow(envObject, value) { + if (envObject.terminatedOrTerminating()) { + return; + } + throw value; +} +var Env = /*#__PURE__*/ (function () { + function Env(ctx, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort) { + this.ctx = ctx; + this.moduleApiVersion = moduleApiVersion; + this.makeDynCall_vppp = makeDynCall_vppp; + this.makeDynCall_vp = makeDynCall_vp; + this.abort = abort; + this.openHandleScopes = 0; + this.instanceData = null; + this.tryCatch = new TryCatch(); + this.refs = 1; + this.reflist = new RefTracker(); + this.finalizing_reflist = new RefTracker(); + this.pendingFinalizers = []; + this.lastError = { + errorCode: 0 /* napi_status.napi_ok */, + engineErrorCode: 0, + engineReserved: 0 + }; + this.inGcFinalizer = false; + this._bindingMap = new WeakMap(); + this.id = 0; + } + /** @virtual */ + Env.prototype.canCallIntoJs = function () { + return true; + }; + Env.prototype.terminatedOrTerminating = function () { + return !this.canCallIntoJs(); + }; + Env.prototype.ref = function () { + this.refs++; + }; + Env.prototype.unref = function () { + this.refs--; + if (this.refs === 0) { + this.dispose(); + } + }; + Env.prototype.ensureHandle = function (value) { + return this.ctx.ensureHandle(value); + }; + Env.prototype.ensureHandleId = function (value) { + return this.ensureHandle(value).id; + }; + Env.prototype.clearLastError = function () { + var lastError = this.lastError; + if (lastError.errorCode !== 0 /* napi_status.napi_ok */) + lastError.errorCode = 0 /* napi_status.napi_ok */; + if (lastError.engineErrorCode !== 0) + lastError.engineErrorCode = 0; + if (lastError.engineReserved !== 0) + lastError.engineReserved = 0; + return 0 /* napi_status.napi_ok */; + }; + Env.prototype.setLastError = function (error_code, engine_error_code, engine_reserved) { + if (engine_error_code === void 0) { engine_error_code = 0; } + if (engine_reserved === void 0) { engine_reserved = 0; } + var lastError = this.lastError; + if (lastError.errorCode !== error_code) + lastError.errorCode = error_code; + if (lastError.engineErrorCode !== engine_error_code) + lastError.engineErrorCode = engine_error_code; + if (lastError.engineReserved !== engine_reserved) + lastError.engineReserved = engine_reserved; + return error_code; + }; + Env.prototype.getReturnStatus = function () { + return !this.tryCatch.hasCaught() ? 0 /* napi_status.napi_ok */ : this.setLastError(10 /* napi_status.napi_pending_exception */); + }; + Env.prototype.callIntoModule = function (fn, handleException) { + if (handleException === void 0) { handleException = handleThrow; } + var openHandleScopesBefore = this.openHandleScopes; + this.clearLastError(); + var r = fn(this); + if (openHandleScopesBefore !== this.openHandleScopes) { + this.abort('open_handle_scopes != open_handle_scopes_before'); + } + if (this.tryCatch.hasCaught()) { + var err = this.tryCatch.extractException(); + handleException(this, err); + } + return r; + }; + Env.prototype.invokeFinalizerFromGC = function (finalizer) { + if (this.moduleApiVersion !== NAPI_VERSION_EXPERIMENTAL) { + this.enqueueFinalizer(finalizer); + } + else { + var saved = this.inGcFinalizer; + this.inGcFinalizer = true; + try { + finalizer.finalize(); + } + finally { + this.inGcFinalizer = saved; + } + } + }; + Env.prototype.checkGCAccess = function () { + if (this.moduleApiVersion === NAPI_VERSION_EXPERIMENTAL && this.inGcFinalizer) { + this.abort('Finalizer is calling a function that may affect GC state.\n' + + 'The finalizers are run directly from GC and must not affect GC ' + + 'state.\n' + + 'Use `node_api_post_finalizer` from inside of the finalizer to work ' + + 'around this issue.\n' + + 'It schedules the call as a new task in the event loop.'); + } + }; + /** @virtual */ + Env.prototype.enqueueFinalizer = function (finalizer) { + if (this.pendingFinalizers.indexOf(finalizer) === -1) { + this.pendingFinalizers.push(finalizer); + } + }; + /** @virtual */ + Env.prototype.dequeueFinalizer = function (finalizer) { + var index = this.pendingFinalizers.indexOf(finalizer); + if (index !== -1) { + this.pendingFinalizers.splice(index, 1); + } + }; + /** @virtual */ + Env.prototype.deleteMe = function () { + RefTracker.finalizeAll(this.finalizing_reflist); + RefTracker.finalizeAll(this.reflist); + this.tryCatch.extractException(); + this.ctx.envStore.remove(this.id); + }; + Env.prototype.dispose = function () { + if (this.id === 0) + return; + this.deleteMe(); + this.finalizing_reflist.dispose(); + this.reflist.dispose(); + this.id = 0; + }; + Env.prototype.initObjectBinding = function (value) { + var binding = { + wrapped: 0, + tag: null + }; + this._bindingMap.set(value, binding); + return binding; + }; + Env.prototype.getObjectBinding = function (value) { + if (this._bindingMap.has(value)) { + return this._bindingMap.get(value); + } + return this.initObjectBinding(value); + }; + Env.prototype.setInstanceData = function (data, finalize_cb, finalize_hint) { + if (this.instanceData) { + this.instanceData.dispose(); + } + this.instanceData = TrackedFinalizer.create(this, finalize_cb, data, finalize_hint); + }; + Env.prototype.getInstanceData = function () { + return this.instanceData ? this.instanceData.data() : 0; + }; + return Env; +}()); +var NodeEnv = /*#__PURE__*/ (function (_super) { + __extends(NodeEnv, _super); + function NodeEnv(ctx, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding) { + var _this = _super.call(this, ctx, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort) || this; + _this.filename = filename; + _this.nodeBinding = nodeBinding; + _this.destructing = false; + _this.finalizationScheduled = false; + return _this; + } + NodeEnv.prototype.deleteMe = function () { + this.destructing = true; + this.drainFinalizerQueue(); + _super.prototype.deleteMe.call(this); + }; + NodeEnv.prototype.canCallIntoJs = function () { + return _super.prototype.canCallIntoJs.call(this) && this.ctx.canCallIntoJs(); + }; + NodeEnv.prototype.triggerFatalException = function (err) { + if (this.nodeBinding) { + this.nodeBinding.napi.fatalException(err); + } + else { + if (typeof process === 'object' && process !== null && typeof process._fatalException === 'function') { + var handled = process._fatalException(err); + if (!handled) { + console.error(err); + process.exit(1); + } + } + else { + throw err; + } + } + }; + NodeEnv.prototype.callbackIntoModule = function (enforceUncaughtExceptionPolicy, fn) { + return this.callIntoModule(fn, function (envObject, err) { + if (envObject.terminatedOrTerminating()) { + return; + } + var hasProcess = typeof process === 'object' && process !== null; + var hasForceFlag = hasProcess ? Boolean(process.execArgv && (process.execArgv.indexOf('--force-node-api-uncaught-exceptions-policy') !== -1)) : false; + if (envObject.moduleApiVersion < 10 && !hasForceFlag && !enforceUncaughtExceptionPolicy) { + var warn = hasProcess && typeof process.emitWarning === 'function' + ? process.emitWarning + : function (warning, type, code) { + if (warning instanceof Error) { + console.warn(warning.toString()); + } + else { + var prefix = code ? "[".concat(code, "] ") : ''; + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + console.warn("".concat(prefix).concat(type || 'Warning', ": ").concat(warning)); + } + }; + warn('Uncaught Node-API callback exception detected, please run node with option --force-node-api-uncaught-exceptions-policy=true to handle those exceptions properly.', 'DeprecationWarning', 'DEP0168'); + return; + } + envObject.triggerFatalException(err); + }); + }; + NodeEnv.prototype.callFinalizer = function (cb, data, hint) { + this.callFinalizerInternal(1, cb, data, hint); + }; + NodeEnv.prototype.callFinalizerInternal = function (forceUncaught, cb, data, hint) { + var f = this.makeDynCall_vppp(cb); + var env = this.id; + var scope = this.ctx.openScope(this); + try { + this.callbackIntoModule(Boolean(forceUncaught), function () { f(env, data, hint); }); + } + finally { + this.ctx.closeScope(this, scope); + } + }; + NodeEnv.prototype.enqueueFinalizer = function (finalizer) { + var _this = this; + _super.prototype.enqueueFinalizer.call(this, finalizer); + if (!this.finalizationScheduled && !this.destructing) { + this.finalizationScheduled = true; + this.ref(); + _setImmediate(function () { + _this.finalizationScheduled = false; + _this.unref(); + _this.drainFinalizerQueue(); + }); + } + }; + NodeEnv.prototype.drainFinalizerQueue = function () { + while (this.pendingFinalizers.length > 0) { + var refTracker = this.pendingFinalizers.shift(); + refTracker.finalize(); + } + }; + return NodeEnv; +}(Env)); +function newEnv(ctx, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding) { + moduleApiVersion = typeof moduleApiVersion !== 'number' ? NODE_API_DEFAULT_MODULE_API_VERSION : moduleApiVersion; + // Validate module_api_version. + if (moduleApiVersion < NODE_API_DEFAULT_MODULE_API_VERSION) { + moduleApiVersion = NODE_API_DEFAULT_MODULE_API_VERSION; + } + else if (moduleApiVersion > NODE_API_SUPPORTED_VERSION_MAX && moduleApiVersion !== NAPI_VERSION_EXPERIMENTAL) { + throwNodeApiVersionError(filename, moduleApiVersion); + } + var env = new NodeEnv(ctx, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding); + ctx.envStore.add(env); + ctx.addCleanupHook(env, function () { env.unref(); }, 0); + return env; +} + +var EmnapiError = /*#__PURE__*/ (function (_super) { + __extends(EmnapiError, _super); + function EmnapiError(message) { + var _newTarget = this.constructor; + var _this = _super.call(this, message) || this; + var ErrorConstructor = _newTarget; + var proto = ErrorConstructor.prototype; + if (!(_this instanceof EmnapiError)) { + var setPrototypeOf = Object.setPrototypeOf; + if (typeof setPrototypeOf === 'function') { + setPrototypeOf.call(Object, _this, proto); + } + else { + // eslint-disable-next-line no-proto + _this.__proto__ = proto; + } + if (typeof Error.captureStackTrace === 'function') { + Error.captureStackTrace(_this, ErrorConstructor); + } + } + return _this; + } + return EmnapiError; +}(Error)); +Object.defineProperty(EmnapiError.prototype, 'name', { + configurable: true, + writable: true, + value: 'EmnapiError' +}); +var NotSupportWeakRefError = /*#__PURE__*/ (function (_super) { + __extends(NotSupportWeakRefError, _super); + function NotSupportWeakRefError(api, message) { + return _super.call(this, "".concat(api, ": The current runtime does not support \"FinalizationRegistry\" and \"WeakRef\".").concat(message ? " ".concat(message) : '')) || this; + } + return NotSupportWeakRefError; +}(EmnapiError)); +Object.defineProperty(NotSupportWeakRefError.prototype, 'name', { + configurable: true, + writable: true, + value: 'NotSupportWeakRefError' +}); +var NotSupportBufferError = /*#__PURE__*/ (function (_super) { + __extends(NotSupportBufferError, _super); + function NotSupportBufferError(api, message) { + return _super.call(this, "".concat(api, ": The current runtime does not support \"Buffer\". Consider using buffer polyfill to make sure `globalThis.Buffer` is defined.").concat(message ? " ".concat(message) : '')) || this; + } + return NotSupportBufferError; +}(EmnapiError)); +Object.defineProperty(NotSupportBufferError.prototype, 'name', { + configurable: true, + writable: true, + value: 'NotSupportBufferError' +}); + +var StrongRef = /*#__PURE__*/ (function () { + function StrongRef(value) { + this._value = value; + } + StrongRef.prototype.deref = function () { + return this._value; + }; + StrongRef.prototype.dispose = function () { + this._value = undefined; + }; + return StrongRef; +}()); +var Persistent = /*#__PURE__*/ (function () { + function Persistent(value) { + this._ref = new StrongRef(value); + } + Persistent.prototype.setWeak = function (param, callback) { + if (!supportFinalizer || this._ref === undefined || this._ref instanceof WeakRef) + return; + var value = this._ref.deref(); + try { + Persistent._registry.register(value, this, this); + var weakRef = new WeakRef(value); + this._ref.dispose(); + this._ref = weakRef; + this._param = param; + this._callback = callback; + } + catch (err) { + if (typeof value === 'symbol') ; + else { + throw err; + } + } + }; + Persistent.prototype.clearWeak = function () { + if (!supportFinalizer || this._ref === undefined) + return; + if (this._ref instanceof WeakRef) { + try { + Persistent._registry.unregister(this); + } + catch (_) { } + this._param = undefined; + this._callback = undefined; + var value = this._ref.deref(); + if (value === undefined) { + this._ref = value; + } + else { + this._ref = new StrongRef(value); + } + } + }; + Persistent.prototype.reset = function () { + if (supportFinalizer) { + try { + Persistent._registry.unregister(this); + } + catch (_) { } + } + this._param = undefined; + this._callback = undefined; + if (this._ref instanceof StrongRef) { + this._ref.dispose(); + } + this._ref = undefined; + }; + Persistent.prototype.isEmpty = function () { + return this._ref === undefined; + }; + Persistent.prototype.deref = function () { + if (this._ref === undefined) + return undefined; + return this._ref.deref(); + }; + Persistent._registry = supportFinalizer + ? new FinalizationRegistry(function (value) { + value._ref = undefined; + var callback = value._callback; + var param = value._param; + value._callback = undefined; + value._param = undefined; + if (typeof callback === 'function') { + callback(param); + } + }) + : undefined; + return Persistent; +}()); + +var ReferenceOwnership; +(function (ReferenceOwnership) { + ReferenceOwnership[ReferenceOwnership["kRuntime"] = 0] = "kRuntime"; + ReferenceOwnership[ReferenceOwnership["kUserland"] = 1] = "kUserland"; +})(ReferenceOwnership || (ReferenceOwnership = {})); +function canBeHeldWeakly(value) { + return value.isObject() || value.isFunction() || value.isSymbol(); +} +var Reference = /*#__PURE__*/ (function (_super) { + __extends(Reference, _super); + function Reference(envObject, handle_id, initialRefcount, ownership) { + var _this = _super.call(this) || this; + _this.envObject = envObject; + _this._refcount = initialRefcount; + _this._ownership = ownership; + var handle = envObject.ctx.handleStore.get(handle_id); + _this.canBeWeak = canBeHeldWeakly(handle); + _this.persistent = new Persistent(handle.value); + _this.id = 0; + if (initialRefcount === 0) { + _this._setWeak(); + } + return _this; + } + Reference.weakCallback = function (ref) { + ref.persistent.reset(); + ref.invokeFinalizerFromGC(); + }; + Reference.create = function (envObject, handle_id, initialRefcount, ownership, _unused1, _unused2, _unused3) { + var ref = new Reference(envObject, handle_id, initialRefcount, ownership); + envObject.ctx.refStore.add(ref); + ref.link(envObject.reflist); + return ref; + }; + Reference.prototype.ref = function () { + if (this.persistent.isEmpty()) { + return 0; + } + if (++this._refcount === 1 && this.canBeWeak) { + this.persistent.clearWeak(); + } + return this._refcount; + }; + Reference.prototype.unref = function () { + if (this.persistent.isEmpty() || this._refcount === 0) { + return 0; + } + if (--this._refcount === 0) { + this._setWeak(); + } + return this._refcount; + }; + Reference.prototype.get = function (envObject) { + if (envObject === void 0) { envObject = this.envObject; } + if (this.persistent.isEmpty()) { + return 0; + } + var obj = this.persistent.deref(); + var handle = envObject.ensureHandle(obj); + return handle.id; + }; + /** @virtual */ + Reference.prototype.resetFinalizer = function () { }; + /** @virtual */ + Reference.prototype.data = function () { return 0; }; + Reference.prototype.refcount = function () { return this._refcount; }; + Reference.prototype.ownership = function () { return this._ownership; }; + /** @virtual */ + Reference.prototype.callUserFinalizer = function () { }; + /** @virtual */ + Reference.prototype.invokeFinalizerFromGC = function () { + this.finalize(); + }; + Reference.prototype._setWeak = function () { + if (this.canBeWeak) { + this.persistent.setWeak(this, Reference.weakCallback); + } + else { + this.persistent.reset(); + } + }; + Reference.prototype.finalize = function () { + this.persistent.reset(); + var deleteMe = this._ownership === ReferenceOwnership.kRuntime; + this.unlink(); + this.callUserFinalizer(); + if (deleteMe) { + this.dispose(); + } + }; + Reference.prototype.dispose = function () { + if (this.id === 0) + return; + this.unlink(); + this.persistent.reset(); + this.envObject.ctx.refStore.remove(this.id); + _super.prototype.dispose.call(this); + this.envObject = undefined; + this.id = 0; + }; + return Reference; +}(RefTracker)); +var ReferenceWithData = /*#__PURE__*/ (function (_super) { + __extends(ReferenceWithData, _super); + function ReferenceWithData(envObject, value, initialRefcount, ownership, _data) { + var _this = _super.call(this, envObject, value, initialRefcount, ownership) || this; + _this._data = _data; + return _this; + } + ReferenceWithData.create = function (envObject, value, initialRefcount, ownership, data) { + var reference = new ReferenceWithData(envObject, value, initialRefcount, ownership, data); + envObject.ctx.refStore.add(reference); + reference.link(envObject.reflist); + return reference; + }; + ReferenceWithData.prototype.data = function () { + return this._data; + }; + return ReferenceWithData; +}(Reference)); +var ReferenceWithFinalizer = /*#__PURE__*/ (function (_super) { + __extends(ReferenceWithFinalizer, _super); + function ReferenceWithFinalizer(envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint) { + var _this = _super.call(this, envObject, value, initialRefcount, ownership) || this; + _this._finalizer = new Finalizer(envObject, finalize_callback, finalize_data, finalize_hint); + return _this; + } + ReferenceWithFinalizer.create = function (envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint) { + var reference = new ReferenceWithFinalizer(envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint); + envObject.ctx.refStore.add(reference); + reference.link(envObject.finalizing_reflist); + return reference; + }; + ReferenceWithFinalizer.prototype.resetFinalizer = function () { + this._finalizer.resetFinalizer(); + }; + ReferenceWithFinalizer.prototype.data = function () { + return this._finalizer.data(); + }; + ReferenceWithFinalizer.prototype.callUserFinalizer = function () { + this._finalizer.callFinalizer(); + }; + ReferenceWithFinalizer.prototype.invokeFinalizerFromGC = function () { + this._finalizer.envObject.invokeFinalizerFromGC(this); + }; + ReferenceWithFinalizer.prototype.dispose = function () { + if (!this._finalizer) + return; + this._finalizer.envObject.dequeueFinalizer(this); + this._finalizer.dispose(); + _super.prototype.dispose.call(this); + this._finalizer = undefined; + }; + return ReferenceWithFinalizer; +}(Reference)); + +var Deferred = /*#__PURE__*/ (function () { + function Deferred(ctx, value) { + // Plain assignment would invoke inherited setters before these fields + // become own properties. + Object.defineProperties(this, { + id: { + configurable: true, + enumerable: true, + value: 0, + writable: true + }, + ctx: { + configurable: true, + enumerable: true, + value: ctx, + writable: true + }, + value: { + configurable: true, + enumerable: true, + value: value, + writable: true + } + }); + } + Deferred.create = function (ctx, value) { + var deferred = new Deferred(ctx, value); + ctx.deferredStore.add(deferred); + return deferred; + }; + Deferred.prototype.resolve = function (value) { + this.value.resolve(value); + this.dispose(); + }; + Deferred.prototype.reject = function (reason) { + this.value.reject(reason); + this.dispose(); + }; + Deferred.prototype.dispose = function () { + this.ctx.deferredStore.remove(this.id); + this.id = 0; + this.value = null; + this.ctx = null; + }; + return Deferred; +}()); + +var Store = /*#__PURE__*/ (function () { + function Store() { + this._values = [undefined]; + this._values.length = 4; + this._size = 1; + this._freeList = []; + } + Store.prototype.add = function (value) { + var id; + if (this._freeList.length) { + id = this._freeList.shift(); + } + else { + id = this._size; + this._size++; + var capacity = this._values.length; + if (id >= capacity) { + this._values.length = capacity + (capacity >> 1) + 16; + } + } + value.id = id; + this._values[id] = value; + }; + Store.prototype.get = function (id) { + return this._values[id]; + }; + Store.prototype.has = function (id) { + return this._values[id] !== undefined; + }; + Store.prototype.remove = function (id) { + var value = this._values[id]; + if (value) { + value.id = 0; + this._values[id] = undefined; + this._freeList.push(Number(id)); + } + }; + Store.prototype.dispose = function () { + for (var i = 1; i < this._size; ++i) { + var value = this._values[i]; + value === null || value === void 0 ? void 0 : value.dispose(); + } + this._values = [undefined]; + this._size = 1; + this._freeList = []; + }; + return Store; +}()); + +var kMaxReasonableBytes = BigInt(1) << BigInt(60); +var kMinReasonableBytes = -kMaxReasonableBytes; +var ExternalMemory = /*#__PURE__*/ (function () { + function ExternalMemory(onChange) { + this.total = BigInt(0); + this.onChange = onChange !== null && onChange !== void 0 ? onChange : null; + } + ExternalMemory.prototype.adjust = function (changeInBytes) { + changeInBytes = BigInt(changeInBytes); + if (!(kMinReasonableBytes <= changeInBytes && changeInBytes < kMaxReasonableBytes)) { + throw new RangeError("changeInBytes ".concat(changeInBytes, " is out of reasonable range")); + } + var old = this.total; + this.total += changeInBytes; + var amount = this.total; + var onChange = this.onChange; + if (changeInBytes) { + onChange === null || onChange === void 0 ? void 0 : onChange(amount, old, changeInBytes); + } + return amount; + }; + return ExternalMemory; +}()); + +var CleanupHookCallback = /*#__PURE__*/ (function () { + function CleanupHookCallback(envObject, fn, arg, order) { + this.envObject = envObject; + this.fn = fn; + this.arg = arg; + this.order = order; + } + return CleanupHookCallback; +}()); +var CleanupQueue = /*#__PURE__*/ (function () { + function CleanupQueue() { + this._cleanupHooks = []; + this._cleanupHookCounter = 0; + } + CleanupQueue.prototype.empty = function () { + return this._cleanupHooks.length === 0; + }; + CleanupQueue.prototype.add = function (envObject, fn, arg) { + if (this._cleanupHooks.filter(function (hook) { return (hook.envObject === envObject && hook.fn === fn && hook.arg === arg); }).length > 0) { + throw new Error('Can not add same fn and arg twice'); + } + this._cleanupHooks.push(new CleanupHookCallback(envObject, fn, arg, this._cleanupHookCounter++)); + }; + CleanupQueue.prototype.remove = function (envObject, fn, arg) { + for (var i = 0; i < this._cleanupHooks.length; ++i) { + var hook = this._cleanupHooks[i]; + if (hook.envObject === envObject && hook.fn === fn && hook.arg === arg) { + this._cleanupHooks.splice(i, 1); + return; + } + } + }; + CleanupQueue.prototype.drain = function () { + var hooks = this._cleanupHooks.slice(); + hooks.sort(function (a, b) { return (b.order - a.order); }); + for (var i = 0; i < hooks.length; ++i) { + var cb = hooks[i]; + if (typeof cb.fn === 'number') { + cb.envObject.makeDynCall_vp(cb.fn)(cb.arg); + } + else { + cb.fn(cb.arg); + } + this._cleanupHooks.splice(this._cleanupHooks.indexOf(cb), 1); + } + }; + CleanupQueue.prototype.dispose = function () { + this._cleanupHooks.length = 0; + this._cleanupHookCounter = 0; + }; + return CleanupQueue; +}()); +var NodejsWaitingRequestCounter = /*#__PURE__*/ (function () { + function NodejsWaitingRequestCounter() { + this.refHandle = new _MessageChannel().port1; + this.count = 0; + } + NodejsWaitingRequestCounter.prototype.increase = function () { + if (this.count === 0) { + if (this.refHandle.ref) { + this.refHandle.ref(); + } + } + this.count++; + }; + NodejsWaitingRequestCounter.prototype.decrease = function () { + if (this.count === 0) + return; + if (this.count === 1) { + if (this.refHandle.unref) { + this.refHandle.unref(); + } + } + this.count--; + }; + return NodejsWaitingRequestCounter; +}()); +var Context = /*#__PURE__*/ (function () { + function Context(options) { + var _this = this; + this._isStopping = false; + this._canCallIntoJs = true; + this._suppressDestroy = false; + this.envStore = new Store(); + this.scopeStore = new ScopeStore(); + this.refStore = new Store(); + this.deferredStore = new Store(); + this.handleStore = new HandleStore(); + this.feature = { + supportReflect: supportReflect, + supportFinalizer: supportFinalizer, + supportWeakSymbol: supportWeakSymbol, + supportBigInt: supportBigInt, + supportNewFunction: supportNewFunction, + canSetFunctionName: canSetFunctionName, + setImmediate: _setImmediate, + Buffer: _Buffer, + MessageChannel: _MessageChannel + }; + this.cleanupQueue = new CleanupQueue(); + this._externalMemory = new ExternalMemory(options === null || options === void 0 ? void 0 : options.onExternalMemoryChange); + if (typeof process === 'object' && process !== null && typeof process.once === 'function') { + this.refCounter = new NodejsWaitingRequestCounter(); + process.once('beforeExit', function () { + if (!_this._suppressDestroy) { + _this.destroy(); + } + }); + } + } + /** + * Suppress the destroy on `beforeExit` event in Node.js. + * Call this method if you want to keep the context and + * all associated {@link Env | Env} alive, + * this also means that cleanup hooks will not be called. + * After call this method, you should call + * {@link Context.destroy | `Context.prototype.destroy`} method manually. + */ + Context.prototype.suppressDestroy = function () { + this._suppressDestroy = true; + }; + // eslint-disable-next-line @typescript-eslint/explicit-function-return-type + Context.prototype.getRuntimeVersions = function () { + return { + version: version, + NODE_API_SUPPORTED_VERSION_MAX: NODE_API_SUPPORTED_VERSION_MAX, + NAPI_VERSION_EXPERIMENTAL: NAPI_VERSION_EXPERIMENTAL, + NODE_API_DEFAULT_MODULE_API_VERSION: NODE_API_DEFAULT_MODULE_API_VERSION + }; + }; + Context.prototype.createNotSupportWeakRefError = function (api, message) { + return new NotSupportWeakRefError(api, message); + }; + Context.prototype.createNotSupportBufferError = function (api, message) { + return new NotSupportBufferError(api, message); + }; + Context.prototype.createReference = function (envObject, handle_id, initialRefcount, ownership) { + return Reference.create(envObject, handle_id, initialRefcount, ownership); + }; + Context.prototype.createReferenceWithData = function (envObject, handle_id, initialRefcount, ownership, data) { + return ReferenceWithData.create(envObject, handle_id, initialRefcount, ownership, data); + }; + Context.prototype.createReferenceWithFinalizer = function (envObject, handle_id, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint) { + if (finalize_callback === void 0) { finalize_callback = 0; } + if (finalize_data === void 0) { finalize_data = 0; } + if (finalize_hint === void 0) { finalize_hint = 0; } + return ReferenceWithFinalizer.create(envObject, handle_id, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint); + }; + Context.prototype.createDeferred = function (value) { + return Deferred.create(this, value); + }; + Context.prototype.adjustAmountOfExternalAllocatedMemory = function (changeInBytes) { + return this._externalMemory.adjust(changeInBytes); + }; + Context.prototype.createEnv = function (filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding) { + return newEnv(this, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding); + }; + Context.prototype.createTrackedFinalizer = function (envObject, finalize_callback, finalize_data, finalize_hint) { + return TrackedFinalizer.create(envObject, finalize_callback, finalize_data, finalize_hint); + }; + Context.prototype.getCurrentScope = function () { + return this.scopeStore.currentScope; + }; + Context.prototype.addToCurrentScope = function (value) { + return this.scopeStore.currentScope.add(value); + }; + Context.prototype.openScope = function (envObject) { + var scope = this.scopeStore.openScope(this.handleStore); + if (envObject) + envObject.openHandleScopes++; + return scope; + }; + Context.prototype.closeScope = function (envObject, _scope) { + if (envObject && envObject.openHandleScopes === 0) + return; + this.scopeStore.closeScope(); + if (envObject) + envObject.openHandleScopes--; + }; + Context.prototype.ensureHandle = function (value) { + switch (value) { + case undefined: return HandleStore.UNDEFINED; + case null: return HandleStore.NULL; + case true: return HandleStore.TRUE; + case false: return HandleStore.FALSE; + case _global: return HandleStore.GLOBAL; + } + return this.addToCurrentScope(value); + }; + Context.prototype.addCleanupHook = function (envObject, fn, arg) { + this.cleanupQueue.add(envObject, fn, arg); + }; + Context.prototype.removeCleanupHook = function (envObject, fn, arg) { + this.cleanupQueue.remove(envObject, fn, arg); + }; + Context.prototype.runCleanup = function () { + while (!this.cleanupQueue.empty()) { + this.cleanupQueue.drain(); + } + }; + Context.prototype.increaseWaitingRequestCounter = function () { + var _a; + (_a = this.refCounter) === null || _a === void 0 ? void 0 : _a.increase(); + }; + Context.prototype.decreaseWaitingRequestCounter = function () { + var _a; + (_a = this.refCounter) === null || _a === void 0 ? void 0 : _a.decrease(); + }; + Context.prototype.setCanCallIntoJs = function (value) { + this._canCallIntoJs = value; + }; + Context.prototype.setStopping = function (value) { + this._isStopping = value; + }; + Context.prototype.canCallIntoJs = function () { + return this._canCallIntoJs && !this._isStopping; + }; + /** + * Destroy the context and call cleanup hooks. + * Associated {@link Env | Env} will be destroyed. + */ + Context.prototype.destroy = function () { + this.setStopping(true); + this.setCanCallIntoJs(false); + this.runCleanup(); + }; + return Context; +}()); +var defaultContext; +function createContext(options) { + return new Context(options); +} +function getDefaultContext() { + if (!defaultContext) { + defaultContext = createContext(); + } + return defaultContext; +} + +export { ConstHandle, Context, Deferred, EmnapiError, Env, External, Finalizer, Handle, HandleScope, HandleStore, NAPI_VERSION_EXPERIMENTAL, NODE_API_DEFAULT_MODULE_API_VERSION, NODE_API_SUPPORTED_VERSION_MAX, NODE_API_SUPPORTED_VERSION_MIN, NodeEnv, NotSupportBufferError, NotSupportWeakRefError, Persistent, RefTracker, Reference, ReferenceOwnership, ReferenceWithData, ReferenceWithFinalizer, ScopeStore, Store, TrackedFinalizer, TryCatch, createContext, getDefaultContext, getExternalValue, isExternal, isReferenceType, version }; diff --git a/node_modules/@emnapi/runtime/dist/emnapi.iife.d.ts b/node_modules/@emnapi/runtime/dist/emnapi.iife.d.ts new file mode 100644 index 0000000..72d26f2 --- /dev/null +++ b/node_modules/@emnapi/runtime/dist/emnapi.iife.d.ts @@ -0,0 +1,426 @@ +declare namespace emnapi { + +export type CleanupHookCallbackFunction = number | ((arg: number) => void); + +export class ConstHandle extends Handle { + constructor(id: number, value: S); + dispose(): void; +} + +export class Context { + private _isStopping; + private _canCallIntoJs; + private _suppressDestroy; + envStore: Store; + scopeStore: ScopeStore; + refStore: Store; + deferredStore: Store>; + handleStore: HandleStore; + private readonly refCounter?; + private readonly cleanupQueue; + private readonly _externalMemory; + feature: { + supportReflect: boolean; + supportFinalizer: boolean; + supportWeakSymbol: boolean; + supportBigInt: boolean; + supportNewFunction: boolean; + canSetFunctionName: boolean; + setImmediate: (callback: () => void) => void; + Buffer: BufferCtor | undefined; + MessageChannel: { + new (): MessageChannel; + prototype: MessageChannel; + } | undefined; + }; + constructor(options?: ContextOptions); + /** + * Suppress the destroy on `beforeExit` event in Node.js. + * Call this method if you want to keep the context and + * all associated {@link Env | Env} alive, + * this also means that cleanup hooks will not be called. + * After call this method, you should call + * {@link Context.destroy | `Context.prototype.destroy`} method manually. + */ + suppressDestroy(): void; + getRuntimeVersions(): { + version: string; + NODE_API_SUPPORTED_VERSION_MAX: Version; + NAPI_VERSION_EXPERIMENTAL: Version; + NODE_API_DEFAULT_MODULE_API_VERSION: Version; + }; + createNotSupportWeakRefError(api: string, message: string): NotSupportWeakRefError; + createNotSupportBufferError(api: string, message: string): NotSupportBufferError; + createReference(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership): Reference; + createReferenceWithData(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, data: void_p): Reference; + createReferenceWithFinalizer(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, finalize_callback?: napi_finalize, finalize_data?: void_p, finalize_hint?: void_p): Reference; + createDeferred(value: IDeferrdValue): Deferred; + adjustAmountOfExternalAllocatedMemory(changeInBytes: number | bigint): bigint; + createEnv(filename: string, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never, nodeBinding?: any): Env; + createTrackedFinalizer(envObject: Env, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): TrackedFinalizer; + getCurrentScope(): HandleScope | null; + addToCurrentScope(value: V): Handle; + openScope(envObject?: Env): HandleScope; + closeScope(envObject?: Env, _scope?: HandleScope): void; + ensureHandle(value: S): Handle; + addCleanupHook(envObject: Env, fn: CleanupHookCallbackFunction, arg: number): void; + removeCleanupHook(envObject: Env, fn: CleanupHookCallbackFunction, arg: number): void; + runCleanup(): void; + increaseWaitingRequestCounter(): void; + decreaseWaitingRequestCounter(): void; + setCanCallIntoJs(value: boolean): void; + setStopping(value: boolean): void; + canCallIntoJs(): boolean; + /** + * Destroy the context and call cleanup hooks. + * Associated {@link Env | Env} will be destroyed. + */ + destroy(): void; +} + +export interface ContextOptions { + onExternalMemoryChange?: (current: bigint, old: bigint, delta: bigint) => any; +} + +export function createContext(options?: ContextOptions): Context; + +export class Deferred implements IStoreValue { + static create(ctx: Context, value: IDeferrdValue): Deferred; + id: number; + ctx: Context; + value: IDeferrdValue; + constructor(ctx: Context, value: IDeferrdValue); + resolve(value: T): void; + reject(reason?: any): void; + dispose(): void; +} + +export class EmnapiError extends Error { + constructor(message?: string); +} + +export abstract class Env implements IStoreValue { + readonly ctx: Context; + moduleApiVersion: number; + makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void; + makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void; + abort: (msg?: string) => never; + id: number; + openHandleScopes: number; + instanceData: TrackedFinalizer | null; + tryCatch: TryCatch; + refs: number; + reflist: RefTracker; + finalizing_reflist: RefTracker; + pendingFinalizers: RefTracker[]; + lastError: { + errorCode: napi_status; + engineErrorCode: number; + engineReserved: Ptr; + }; + inGcFinalizer: boolean; + constructor(ctx: Context, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never); + /** @virtual */ + canCallIntoJs(): boolean; + terminatedOrTerminating(): boolean; + ref(): void; + unref(): void; + ensureHandle(value: S): Handle; + ensureHandleId(value: any): napi_value; + clearLastError(): napi_status; + setLastError(error_code: napi_status, engine_error_code?: uint32_t, engine_reserved?: void_p): napi_status; + getReturnStatus(): napi_status; + callIntoModule(fn: (env: Env) => T, handleException?: (envObject: Env, value: any) => void): T; + /** @virtual */ + abstract callFinalizer(cb: napi_finalize, data: void_p, hint: void_p): void; + invokeFinalizerFromGC(finalizer: RefTracker): void; + checkGCAccess(): void; + /** @virtual */ + enqueueFinalizer(finalizer: RefTracker): void; + /** @virtual */ + dequeueFinalizer(finalizer: RefTracker): void; + /** @virtual */ + deleteMe(): void; + dispose(): void; + private readonly _bindingMap; + initObjectBinding(value: S): IReferenceBinding; + getObjectBinding(value: S): IReferenceBinding; + setInstanceData(data: number, finalize_cb: number, finalize_hint: number): void; + getInstanceData(): number; +} + +/** @public */ +interface External_2 extends Record { +} + +/** @public */ +const External_2: { + new (value: number | bigint): External_2; + prototype: null; +}; +export { External_2 as External } + +export class Finalizer { + envObject: Env; + private _finalizeCallback; + private _finalizeData; + private _finalizeHint; + private _makeDynCall_vppp; + constructor(envObject: Env, _finalizeCallback?: napi_finalize, _finalizeData?: void_p, _finalizeHint?: void_p); + callback(): napi_finalize; + data(): void_p; + hint(): void_p; + resetEnv(): void; + resetFinalizer(): void; + callFinalizer(): void; + dispose(): void; +} + +export function getDefaultContext(): Context; + +/** @public */ +export function getExternalValue(external: External_2): number | bigint; + +export class Handle { + id: number; + value: S; + constructor(id: number, value: S); + data(): void_p; + isNumber(): boolean; + isBigInt(): boolean; + isString(): boolean; + isFunction(): boolean; + isExternal(): boolean; + isObject(): boolean; + isArray(): boolean; + isArrayBuffer(): boolean; + isTypedArray(): boolean; + isBuffer(BufferConstructor?: BufferCtor): boolean; + isDataView(): boolean; + isDate(): boolean; + isPromise(): boolean; + isBoolean(): boolean; + isUndefined(): boolean; + isSymbol(): boolean; + isNull(): boolean; + dispose(): void; +} + +export class HandleScope { + handleStore: HandleStore; + id: number; + parent: HandleScope | null; + child: HandleScope | null; + start: number; + end: number; + private _escapeCalled; + callbackInfo: ICallbackInfo; + constructor(handleStore: HandleStore, id: number, parentScope: HandleScope | null, start: number, end?: number); + add(value: V): Handle; + addExternal(data: void_p): Handle; + dispose(): void; + escape(handle: number): Handle | null; + escapeCalled(): boolean; +} + +export class HandleStore { + static UNDEFINED: ConstHandle; + static NULL: ConstHandle; + static FALSE: ConstHandle; + static TRUE: ConstHandle; + static GLOBAL: ConstHandle; + static MIN_ID: 6; + private readonly _values; + private _next; + push(value: S): Handle; + erase(start: number, end: number): void; + get(id: Ptr): Handle | undefined; + swap(a: number, b: number): void; + dispose(): void; +} + +export interface ICallbackInfo { + thiz: any; + data: void_p; + args: ArrayLike; + fn: Function; +} + +export interface IDeferrdValue { + resolve: (value: T) => void; + reject: (reason?: any) => void; +} + +export interface IReferenceBinding { + wrapped: number; + tag: Uint32Array | null; +} + +/** @public */ +export function isExternal(object: unknown): object is External_2; + +export function isReferenceType(v: any): v is object; + +export interface IStoreValue { + id: number; + dispose(): void; + [x: string]: any; +} + +export const NAPI_VERSION_EXPERIMENTAL = Version.NAPI_VERSION_EXPERIMENTAL; + +export const NODE_API_DEFAULT_MODULE_API_VERSION = Version.NODE_API_DEFAULT_MODULE_API_VERSION; + +export const NODE_API_SUPPORTED_VERSION_MAX = Version.NODE_API_SUPPORTED_VERSION_MAX; + +export const NODE_API_SUPPORTED_VERSION_MIN = Version.NODE_API_SUPPORTED_VERSION_MIN; + +export class NodeEnv extends Env { + filename: string; + private readonly nodeBinding?; + destructing: boolean; + finalizationScheduled: boolean; + constructor(ctx: Context, filename: string, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never, nodeBinding?: any); + deleteMe(): void; + canCallIntoJs(): boolean; + triggerFatalException(err: any): void; + callbackIntoModule(enforceUncaughtExceptionPolicy: boolean, fn: (env: Env) => T): T; + callFinalizer(cb: napi_finalize, data: void_p, hint: void_p): void; + callFinalizerInternal(forceUncaught: int, cb: napi_finalize, data: void_p, hint: void_p): void; + enqueueFinalizer(finalizer: RefTracker): void; + drainFinalizerQueue(): void; +} + +export class NotSupportBufferError extends EmnapiError { + constructor(api: string, message: string); +} + +export class NotSupportWeakRefError extends EmnapiError { + constructor(api: string, message: string); +} + +export class Persistent { + private _ref; + private _param; + private _callback; + private static readonly _registry; + constructor(value: T); + setWeak

(param: P, callback: (param: P) => void): void; + clearWeak(): void; + reset(): void; + isEmpty(): boolean; + deref(): T | undefined; +} + +export class Reference extends RefTracker implements IStoreValue { + private static weakCallback; + id: number; + envObject: Env; + private readonly canBeWeak; + private _refcount; + private readonly _ownership; + persistent: Persistent; + static create(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, _unused1?: void_p, _unused2?: void_p, _unused3?: void_p): Reference; + protected constructor(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership); + ref(): number; + unref(): number; + get(envObject?: Env): napi_value; + /** @virtual */ + resetFinalizer(): void; + /** @virtual */ + data(): void_p; + refcount(): number; + ownership(): ReferenceOwnership; + /** @virtual */ + protected callUserFinalizer(): void; + /** @virtual */ + protected invokeFinalizerFromGC(): void; + private _setWeak; + finalize(): void; + dispose(): void; +} + +export enum ReferenceOwnership { + kRuntime = 0, + kUserland = 1 +} + +export class ReferenceWithData extends Reference { + private readonly _data; + static create(envObject: Env, value: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, data: void_p): ReferenceWithData; + private constructor(); + data(): void_p; +} + +export class ReferenceWithFinalizer extends Reference { + private _finalizer; + static create(envObject: Env, value: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): ReferenceWithFinalizer; + private constructor(); + resetFinalizer(): void; + data(): void_p; + protected callUserFinalizer(): void; + protected invokeFinalizerFromGC(): void; + dispose(): void; +} + +export class RefTracker { + /** @virtual */ + dispose(): void; + /** @virtual */ + finalize(): void; + private _next; + private _prev; + link(list: RefTracker): void; + unlink(): void; + static finalizeAll(list: RefTracker): void; +} + +export class ScopeStore { + private readonly _rootScope; + currentScope: HandleScope; + private readonly _values; + constructor(); + get(id: number): HandleScope | undefined; + openScope(handleStore: HandleStore): HandleScope; + closeScope(): void; + dispose(): void; +} + +export class Store { + protected _values: Array; + private _freeList; + private _size; + constructor(); + add(value: V): void; + get(id: Ptr): V | undefined; + has(id: Ptr): boolean; + remove(id: Ptr): void; + dispose(): void; +} + +export class TrackedFinalizer extends RefTracker { + private _finalizer; + static create(envObject: Env, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): TrackedFinalizer; + private constructor(); + data(): void_p; + dispose(): void; + finalize(): void; +} + +export class TryCatch { + private _exception; + private _caught; + isEmpty(): boolean; + hasCaught(): boolean; + exception(): any; + setError(err: any): void; + reset(): void; + extractException(): any; +} + +export const version: string; + + + + +} \ No newline at end of file diff --git a/node_modules/@emnapi/runtime/dist/emnapi.iife.js b/node_modules/@emnapi/runtime/dist/emnapi.iife.js new file mode 100644 index 0000000..c39b505 --- /dev/null +++ b/node_modules/@emnapi/runtime/dist/emnapi.iife.js @@ -0,0 +1,1528 @@ +var emnapi = (function (exports) { + + /****************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise, SuppressedError, Symbol, Iterator */ + + var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + + function __extends(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; + }; + + var externalValue = new WeakMap(); + /** @public */ + function isExternal(object) { + return externalValue.has(object); + } + /** @public */ // eslint-disable-next-line @typescript-eslint/no-redeclare + var External = (function () { + function External(value) { + Object.setPrototypeOf(this, null); + externalValue.set(this, value); + } + External.prototype = null; + return External; + })(); + /** @public */ + function getExternalValue(external) { + if (!isExternal(external)) { + throw new TypeError('not external'); + } + return externalValue.get(external); + } + + var supportNewFunction = /*#__PURE__*/ (function () { + var f; + try { + f = new Function(); + } + catch (_) { + return false; + } + return typeof f === 'function'; + })(); + var _global = /*#__PURE__*/ (function () { + if (typeof globalThis !== 'undefined') + return globalThis; + var g = (function () { return this; })(); + if (!g && supportNewFunction) { + try { + g = new Function('return this')(); + } + catch (_) { } + } + if (!g) { + if (typeof __webpack_public_path__ === 'undefined') { + if (typeof global !== 'undefined') + return global; + } + if (typeof window !== 'undefined') + return window; + if (typeof self !== 'undefined') + return self; + } + return g; + })(); + var TryCatch = /*#__PURE__*/ (function () { + function TryCatch() { + this._exception = undefined; + this._caught = false; + } + TryCatch.prototype.isEmpty = function () { + return !this._caught; + }; + TryCatch.prototype.hasCaught = function () { + return this._caught; + }; + TryCatch.prototype.exception = function () { + return this._exception; + }; + TryCatch.prototype.setError = function (err) { + this._caught = true; + this._exception = err; + }; + TryCatch.prototype.reset = function () { + this._caught = false; + this._exception = undefined; + }; + TryCatch.prototype.extractException = function () { + var e = this._exception; + this.reset(); + return e; + }; + return TryCatch; + }()); + var canSetFunctionName = /*#__PURE__*/ (function () { + var _a; + try { + return Boolean((_a = Object.getOwnPropertyDescriptor(Function.prototype, 'name')) === null || _a === void 0 ? void 0 : _a.configurable); + } + catch (_) { + return false; + } + })(); + var supportReflect = typeof Reflect === 'object'; + var supportFinalizer = (typeof FinalizationRegistry !== 'undefined') && (typeof WeakRef !== 'undefined'); + var supportWeakSymbol = /*#__PURE__*/ (function () { + try { + // eslint-disable-next-line symbol-description + var sym = Symbol(); + // eslint-disable-next-line no-new + new WeakRef(sym); + new WeakMap().set(sym, undefined); + } + catch (_) { + return false; + } + return true; + })(); + var supportBigInt = typeof BigInt !== 'undefined'; + function isReferenceType(v) { + return (typeof v === 'object' && v !== null) || typeof v === 'function'; + } + var _require = /*#__PURE__*/ (function () { + var nativeRequire; + if (typeof __webpack_public_path__ !== 'undefined') { + nativeRequire = (function () { + return typeof __non_webpack_require__ !== 'undefined' ? __non_webpack_require__ : undefined; + })(); + } + else { + nativeRequire = (function () { + return typeof __webpack_public_path__ !== 'undefined' ? (typeof __non_webpack_require__ !== 'undefined' ? __non_webpack_require__ : undefined) : (typeof require !== 'undefined' ? require : undefined); + })(); + } + return nativeRequire; + })(); + var _MessageChannel = typeof MessageChannel === 'function' + ? MessageChannel + : /*#__PURE__*/ (function () { + try { + return _require('worker_threads').MessageChannel; + } + catch (_) { } + return undefined; + })(); + var _setImmediate = typeof setImmediate === 'function' + ? setImmediate.bind(_global) + : function (callback) { + if (typeof callback !== 'function') { + throw new TypeError('The "callback" argument must be of type function'); + } + if (_MessageChannel) { + var channel_1 = new _MessageChannel(); + channel_1.port1.onmessage = function () { + channel_1.port1.onmessage = null; + channel_1 = undefined; + callback(); + }; + channel_1.port2.postMessage(null); + } + else { + setTimeout(callback, 0); + } + }; + var _Buffer = typeof Buffer === 'function' + ? Buffer + : /*#__PURE__*/ (function () { + try { + return _require('buffer').Buffer; + } + catch (_) { } + return undefined; + })(); + var version = "1.11.3"; + var NODE_API_SUPPORTED_VERSION_MIN = 1 /* Version.NODE_API_SUPPORTED_VERSION_MIN */; + var NODE_API_SUPPORTED_VERSION_MAX = 10 /* Version.NODE_API_SUPPORTED_VERSION_MAX */; + var NAPI_VERSION_EXPERIMENTAL = 2147483647 /* Version.NAPI_VERSION_EXPERIMENTAL */; + var NODE_API_DEFAULT_MODULE_API_VERSION = 8 /* Version.NODE_API_DEFAULT_MODULE_API_VERSION */; + + var Handle = /*#__PURE__*/ (function () { + function Handle(id, value) { + this.id = id; + this.value = value; + } + Handle.prototype.data = function () { + return getExternalValue(this.value); + }; + Handle.prototype.isNumber = function () { + return typeof this.value === 'number'; + }; + Handle.prototype.isBigInt = function () { + return typeof this.value === 'bigint'; + }; + Handle.prototype.isString = function () { + return typeof this.value === 'string'; + }; + Handle.prototype.isFunction = function () { + return typeof this.value === 'function'; + }; + Handle.prototype.isExternal = function () { + return isExternal(this.value); + }; + Handle.prototype.isObject = function () { + return typeof this.value === 'object' && this.value !== null; + }; + Handle.prototype.isArray = function () { + return Array.isArray(this.value); + }; + Handle.prototype.isArrayBuffer = function () { + return (this.value instanceof ArrayBuffer); + }; + Handle.prototype.isTypedArray = function () { + return (ArrayBuffer.isView(this.value)) && !(this.value instanceof DataView); + }; + Handle.prototype.isBuffer = function (BufferConstructor) { + if (ArrayBuffer.isView(this.value)) + return true; + BufferConstructor !== null && BufferConstructor !== void 0 ? BufferConstructor : (BufferConstructor = _Buffer); + return typeof BufferConstructor === 'function' && BufferConstructor.isBuffer(this.value); + }; + Handle.prototype.isDataView = function () { + return (this.value instanceof DataView); + }; + Handle.prototype.isDate = function () { + return (this.value instanceof Date); + }; + Handle.prototype.isPromise = function () { + return (this.value instanceof Promise); + }; + Handle.prototype.isBoolean = function () { + return typeof this.value === 'boolean'; + }; + Handle.prototype.isUndefined = function () { + return this.value === undefined; + }; + Handle.prototype.isSymbol = function () { + return typeof this.value === 'symbol'; + }; + Handle.prototype.isNull = function () { + return this.value === null; + }; + Handle.prototype.dispose = function () { + this.value = undefined; + }; + return Handle; + }()); + var ConstHandle = /*#__PURE__*/ (function (_super) { + __extends(ConstHandle, _super); + function ConstHandle(id, value) { + return _super.call(this, id, value) || this; + } + ConstHandle.prototype.dispose = function () { }; + return ConstHandle; + }(Handle)); + var HandleStore = /*#__PURE__*/ (function () { + function HandleStore() { + this._values = [ + undefined, + HandleStore.UNDEFINED, + HandleStore.NULL, + HandleStore.FALSE, + HandleStore.TRUE, + HandleStore.GLOBAL + ]; + this._next = HandleStore.MIN_ID; + } + HandleStore.prototype.push = function (value) { + var h; + var next = this._next; + var values = this._values; + if (next < values.length) { + h = values[next]; + h.value = value; + } + else { + h = new Handle(next, value); + values[next] = h; + } + this._next++; + return h; + }; + HandleStore.prototype.erase = function (start, end) { + this._next = start; + var values = this._values; + for (var i = start; i < end; ++i) { + values[i].dispose(); + } + }; + HandleStore.prototype.get = function (id) { + return this._values[id]; + }; + HandleStore.prototype.swap = function (a, b) { + var values = this._values; + var h = values[a]; + values[a] = values[b]; + values[a].id = Number(a); + values[b] = h; + h.id = Number(b); + }; + HandleStore.prototype.dispose = function () { + this._values.length = HandleStore.MIN_ID; + this._next = HandleStore.MIN_ID; + }; + HandleStore.UNDEFINED = new ConstHandle(1 /* GlobalHandle.UNDEFINED */, undefined); + HandleStore.NULL = new ConstHandle(2 /* GlobalHandle.NULL */, null); + HandleStore.FALSE = new ConstHandle(3 /* GlobalHandle.FALSE */, false); + HandleStore.TRUE = new ConstHandle(4 /* GlobalHandle.TRUE */, true); + HandleStore.GLOBAL = new ConstHandle(5 /* GlobalHandle.GLOBAL */, _global); + HandleStore.MIN_ID = 6; + return HandleStore; + }()); + + var HandleScope = /*#__PURE__*/ (function () { + function HandleScope(handleStore, id, parentScope, start, end) { + if (end === void 0) { end = start; } + this.handleStore = handleStore; + this.id = id; + this.parent = parentScope; + this.child = null; + if (parentScope !== null) + parentScope.child = this; + this.start = start; + this.end = end; + this._escapeCalled = false; + this.callbackInfo = { + thiz: undefined, + data: 0, + args: undefined, + fn: undefined + }; + } + HandleScope.prototype.add = function (value) { + var h = this.handleStore.push(value); + this.end++; + return h; + }; + HandleScope.prototype.addExternal = function (data) { + return this.add(new External(data)); + }; + HandleScope.prototype.dispose = function () { + if (this._escapeCalled) + this._escapeCalled = false; + if (this.start === this.end) + return; + this.handleStore.erase(this.start, this.end); + }; + HandleScope.prototype.escape = function (handle) { + if (this._escapeCalled) + return null; + this._escapeCalled = true; + if (handle < this.start || handle >= this.end) { + return null; + } + this.handleStore.swap(handle, this.start); + var h = this.handleStore.get(this.start); + this.start++; + this.parent.end++; + return h; + }; + HandleScope.prototype.escapeCalled = function () { + return this._escapeCalled; + }; + return HandleScope; + }()); + + var ScopeStore = /*#__PURE__*/ (function () { + function ScopeStore() { + this._rootScope = new HandleScope(null, 0, null, 1, HandleStore.MIN_ID); + this.currentScope = this._rootScope; + this._values = [undefined]; + } + ScopeStore.prototype.get = function (id) { + return this._values[id]; + }; + ScopeStore.prototype.openScope = function (handleStore) { + var currentScope = this.currentScope; + var scope = currentScope.child; + if (scope !== null) { + scope.start = scope.end = currentScope.end; + } + else { + var id = currentScope.id + 1; + scope = new HandleScope(handleStore, id, currentScope, currentScope.end); + this._values[id] = scope; + } + this.currentScope = scope; + return scope; + }; + ScopeStore.prototype.closeScope = function () { + var scope = this.currentScope; + this.currentScope = scope.parent; + scope.dispose(); + }; + ScopeStore.prototype.dispose = function () { + this.currentScope = this._rootScope; + this._values.length = 1; + }; + return ScopeStore; + }()); + + var RefTracker = /*#__PURE__*/ (function () { + function RefTracker() { + this._next = null; + this._prev = null; + } + /** @virtual */ + RefTracker.prototype.dispose = function () { }; + /** @virtual */ + RefTracker.prototype.finalize = function () { }; + RefTracker.prototype.link = function (list) { + this._prev = list; + this._next = list._next; + if (this._next !== null) { + this._next._prev = this; + } + list._next = this; + }; + RefTracker.prototype.unlink = function () { + if (this._prev !== null) { + this._prev._next = this._next; + } + if (this._next !== null) { + this._next._prev = this._prev; + } + this._prev = null; + this._next = null; + }; + RefTracker.finalizeAll = function (list) { + while (list._next !== null) { + list._next.finalize(); + } + }; + return RefTracker; + }()); + + var Finalizer = /*#__PURE__*/ (function () { + function Finalizer(envObject, _finalizeCallback, _finalizeData, _finalizeHint) { + if (_finalizeCallback === void 0) { _finalizeCallback = 0; } + if (_finalizeData === void 0) { _finalizeData = 0; } + if (_finalizeHint === void 0) { _finalizeHint = 0; } + this.envObject = envObject; + this._finalizeCallback = _finalizeCallback; + this._finalizeData = _finalizeData; + this._finalizeHint = _finalizeHint; + this._makeDynCall_vppp = envObject.makeDynCall_vppp; + } + Finalizer.prototype.callback = function () { return this._finalizeCallback; }; + Finalizer.prototype.data = function () { return this._finalizeData; }; + Finalizer.prototype.hint = function () { return this._finalizeHint; }; + Finalizer.prototype.resetEnv = function () { + this.envObject = undefined; + }; + Finalizer.prototype.resetFinalizer = function () { + this._finalizeCallback = 0; + this._finalizeData = 0; + this._finalizeHint = 0; + }; + Finalizer.prototype.callFinalizer = function () { + var finalize_callback = this._finalizeCallback; + var finalize_data = this._finalizeData; + var finalize_hint = this._finalizeHint; + this.resetFinalizer(); + if (!finalize_callback) + return; + var fini = Number(finalize_callback); + if (!this.envObject) { + this._makeDynCall_vppp(fini)(0, finalize_data, finalize_hint); + } + else { + this.envObject.callFinalizer(fini, finalize_data, finalize_hint); + } + }; + Finalizer.prototype.dispose = function () { + this.envObject = undefined; + this._makeDynCall_vppp = undefined; + }; + return Finalizer; + }()); + + var TrackedFinalizer = /*#__PURE__*/ (function (_super) { + __extends(TrackedFinalizer, _super); + function TrackedFinalizer(envObject, finalize_callback, finalize_data, finalize_hint) { + var _this = _super.call(this) || this; + _this._finalizer = new Finalizer(envObject, finalize_callback, finalize_data, finalize_hint); + return _this; + } + TrackedFinalizer.create = function (envObject, finalize_callback, finalize_data, finalize_hint) { + var finalizer = new TrackedFinalizer(envObject, finalize_callback, finalize_data, finalize_hint); + finalizer.link(envObject.finalizing_reflist); + return finalizer; + }; + TrackedFinalizer.prototype.data = function () { + return this._finalizer.data(); + }; + TrackedFinalizer.prototype.dispose = function () { + if (!this._finalizer) + return; + this.unlink(); + this._finalizer.envObject.dequeueFinalizer(this); + this._finalizer.dispose(); + this._finalizer = undefined; + _super.prototype.dispose.call(this); + }; + TrackedFinalizer.prototype.finalize = function () { + this.unlink(); + var error; + var caught = false; + try { + this._finalizer.callFinalizer(); + } + catch (err) { + caught = true; + error = err; + } + this.dispose(); + if (caught) { + throw error; + } + }; + return TrackedFinalizer; + }(RefTracker)); + + function throwNodeApiVersionError(moduleName, moduleApiVersion) { + var errorMessage = "".concat(moduleName, " requires Node-API version ").concat(moduleApiVersion, ", but this version of Node.js only supports version ").concat(NODE_API_SUPPORTED_VERSION_MAX, " add-ons."); + throw new Error(errorMessage); + } + function handleThrow(envObject, value) { + if (envObject.terminatedOrTerminating()) { + return; + } + throw value; + } + var Env = /*#__PURE__*/ (function () { + function Env(ctx, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort) { + this.ctx = ctx; + this.moduleApiVersion = moduleApiVersion; + this.makeDynCall_vppp = makeDynCall_vppp; + this.makeDynCall_vp = makeDynCall_vp; + this.abort = abort; + this.openHandleScopes = 0; + this.instanceData = null; + this.tryCatch = new TryCatch(); + this.refs = 1; + this.reflist = new RefTracker(); + this.finalizing_reflist = new RefTracker(); + this.pendingFinalizers = []; + this.lastError = { + errorCode: 0 /* napi_status.napi_ok */, + engineErrorCode: 0, + engineReserved: 0 + }; + this.inGcFinalizer = false; + this._bindingMap = new WeakMap(); + this.id = 0; + } + /** @virtual */ + Env.prototype.canCallIntoJs = function () { + return true; + }; + Env.prototype.terminatedOrTerminating = function () { + return !this.canCallIntoJs(); + }; + Env.prototype.ref = function () { + this.refs++; + }; + Env.prototype.unref = function () { + this.refs--; + if (this.refs === 0) { + this.dispose(); + } + }; + Env.prototype.ensureHandle = function (value) { + return this.ctx.ensureHandle(value); + }; + Env.prototype.ensureHandleId = function (value) { + return this.ensureHandle(value).id; + }; + Env.prototype.clearLastError = function () { + var lastError = this.lastError; + if (lastError.errorCode !== 0 /* napi_status.napi_ok */) + lastError.errorCode = 0 /* napi_status.napi_ok */; + if (lastError.engineErrorCode !== 0) + lastError.engineErrorCode = 0; + if (lastError.engineReserved !== 0) + lastError.engineReserved = 0; + return 0 /* napi_status.napi_ok */; + }; + Env.prototype.setLastError = function (error_code, engine_error_code, engine_reserved) { + if (engine_error_code === void 0) { engine_error_code = 0; } + if (engine_reserved === void 0) { engine_reserved = 0; } + var lastError = this.lastError; + if (lastError.errorCode !== error_code) + lastError.errorCode = error_code; + if (lastError.engineErrorCode !== engine_error_code) + lastError.engineErrorCode = engine_error_code; + if (lastError.engineReserved !== engine_reserved) + lastError.engineReserved = engine_reserved; + return error_code; + }; + Env.prototype.getReturnStatus = function () { + return !this.tryCatch.hasCaught() ? 0 /* napi_status.napi_ok */ : this.setLastError(10 /* napi_status.napi_pending_exception */); + }; + Env.prototype.callIntoModule = function (fn, handleException) { + if (handleException === void 0) { handleException = handleThrow; } + var openHandleScopesBefore = this.openHandleScopes; + this.clearLastError(); + var r = fn(this); + if (openHandleScopesBefore !== this.openHandleScopes) { + this.abort('open_handle_scopes != open_handle_scopes_before'); + } + if (this.tryCatch.hasCaught()) { + var err = this.tryCatch.extractException(); + handleException(this, err); + } + return r; + }; + Env.prototype.invokeFinalizerFromGC = function (finalizer) { + if (this.moduleApiVersion !== NAPI_VERSION_EXPERIMENTAL) { + this.enqueueFinalizer(finalizer); + } + else { + var saved = this.inGcFinalizer; + this.inGcFinalizer = true; + try { + finalizer.finalize(); + } + finally { + this.inGcFinalizer = saved; + } + } + }; + Env.prototype.checkGCAccess = function () { + if (this.moduleApiVersion === NAPI_VERSION_EXPERIMENTAL && this.inGcFinalizer) { + this.abort('Finalizer is calling a function that may affect GC state.\n' + + 'The finalizers are run directly from GC and must not affect GC ' + + 'state.\n' + + 'Use `node_api_post_finalizer` from inside of the finalizer to work ' + + 'around this issue.\n' + + 'It schedules the call as a new task in the event loop.'); + } + }; + /** @virtual */ + Env.prototype.enqueueFinalizer = function (finalizer) { + if (this.pendingFinalizers.indexOf(finalizer) === -1) { + this.pendingFinalizers.push(finalizer); + } + }; + /** @virtual */ + Env.prototype.dequeueFinalizer = function (finalizer) { + var index = this.pendingFinalizers.indexOf(finalizer); + if (index !== -1) { + this.pendingFinalizers.splice(index, 1); + } + }; + /** @virtual */ + Env.prototype.deleteMe = function () { + RefTracker.finalizeAll(this.finalizing_reflist); + RefTracker.finalizeAll(this.reflist); + this.tryCatch.extractException(); + this.ctx.envStore.remove(this.id); + }; + Env.prototype.dispose = function () { + if (this.id === 0) + return; + this.deleteMe(); + this.finalizing_reflist.dispose(); + this.reflist.dispose(); + this.id = 0; + }; + Env.prototype.initObjectBinding = function (value) { + var binding = { + wrapped: 0, + tag: null + }; + this._bindingMap.set(value, binding); + return binding; + }; + Env.prototype.getObjectBinding = function (value) { + if (this._bindingMap.has(value)) { + return this._bindingMap.get(value); + } + return this.initObjectBinding(value); + }; + Env.prototype.setInstanceData = function (data, finalize_cb, finalize_hint) { + if (this.instanceData) { + this.instanceData.dispose(); + } + this.instanceData = TrackedFinalizer.create(this, finalize_cb, data, finalize_hint); + }; + Env.prototype.getInstanceData = function () { + return this.instanceData ? this.instanceData.data() : 0; + }; + return Env; + }()); + var NodeEnv = /*#__PURE__*/ (function (_super) { + __extends(NodeEnv, _super); + function NodeEnv(ctx, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding) { + var _this = _super.call(this, ctx, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort) || this; + _this.filename = filename; + _this.nodeBinding = nodeBinding; + _this.destructing = false; + _this.finalizationScheduled = false; + return _this; + } + NodeEnv.prototype.deleteMe = function () { + this.destructing = true; + this.drainFinalizerQueue(); + _super.prototype.deleteMe.call(this); + }; + NodeEnv.prototype.canCallIntoJs = function () { + return _super.prototype.canCallIntoJs.call(this) && this.ctx.canCallIntoJs(); + }; + NodeEnv.prototype.triggerFatalException = function (err) { + if (this.nodeBinding) { + this.nodeBinding.napi.fatalException(err); + } + else { + if (typeof process === 'object' && process !== null && typeof process._fatalException === 'function') { + var handled = process._fatalException(err); + if (!handled) { + console.error(err); + process.exit(1); + } + } + else { + throw err; + } + } + }; + NodeEnv.prototype.callbackIntoModule = function (enforceUncaughtExceptionPolicy, fn) { + return this.callIntoModule(fn, function (envObject, err) { + if (envObject.terminatedOrTerminating()) { + return; + } + var hasProcess = typeof process === 'object' && process !== null; + var hasForceFlag = hasProcess ? Boolean(process.execArgv && (process.execArgv.indexOf('--force-node-api-uncaught-exceptions-policy') !== -1)) : false; + if (envObject.moduleApiVersion < 10 && !hasForceFlag && !enforceUncaughtExceptionPolicy) { + var warn = hasProcess && typeof process.emitWarning === 'function' + ? process.emitWarning + : function (warning, type, code) { + if (warning instanceof Error) { + console.warn(warning.toString()); + } + else { + var prefix = code ? "[".concat(code, "] ") : ''; + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + console.warn("".concat(prefix).concat(type || 'Warning', ": ").concat(warning)); + } + }; + warn('Uncaught Node-API callback exception detected, please run node with option --force-node-api-uncaught-exceptions-policy=true to handle those exceptions properly.', 'DeprecationWarning', 'DEP0168'); + return; + } + envObject.triggerFatalException(err); + }); + }; + NodeEnv.prototype.callFinalizer = function (cb, data, hint) { + this.callFinalizerInternal(1, cb, data, hint); + }; + NodeEnv.prototype.callFinalizerInternal = function (forceUncaught, cb, data, hint) { + var f = this.makeDynCall_vppp(cb); + var env = this.id; + var scope = this.ctx.openScope(this); + try { + this.callbackIntoModule(Boolean(forceUncaught), function () { f(env, data, hint); }); + } + finally { + this.ctx.closeScope(this, scope); + } + }; + NodeEnv.prototype.enqueueFinalizer = function (finalizer) { + var _this = this; + _super.prototype.enqueueFinalizer.call(this, finalizer); + if (!this.finalizationScheduled && !this.destructing) { + this.finalizationScheduled = true; + this.ref(); + _setImmediate(function () { + _this.finalizationScheduled = false; + _this.unref(); + _this.drainFinalizerQueue(); + }); + } + }; + NodeEnv.prototype.drainFinalizerQueue = function () { + while (this.pendingFinalizers.length > 0) { + var refTracker = this.pendingFinalizers.shift(); + refTracker.finalize(); + } + }; + return NodeEnv; + }(Env)); + function newEnv(ctx, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding) { + moduleApiVersion = typeof moduleApiVersion !== 'number' ? NODE_API_DEFAULT_MODULE_API_VERSION : moduleApiVersion; + // Validate module_api_version. + if (moduleApiVersion < NODE_API_DEFAULT_MODULE_API_VERSION) { + moduleApiVersion = NODE_API_DEFAULT_MODULE_API_VERSION; + } + else if (moduleApiVersion > NODE_API_SUPPORTED_VERSION_MAX && moduleApiVersion !== NAPI_VERSION_EXPERIMENTAL) { + throwNodeApiVersionError(filename, moduleApiVersion); + } + var env = new NodeEnv(ctx, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding); + ctx.envStore.add(env); + ctx.addCleanupHook(env, function () { env.unref(); }, 0); + return env; + } + + var EmnapiError = /*#__PURE__*/ (function (_super) { + __extends(EmnapiError, _super); + function EmnapiError(message) { + var _newTarget = this.constructor; + var _this = _super.call(this, message) || this; + var ErrorConstructor = _newTarget; + var proto = ErrorConstructor.prototype; + if (!(_this instanceof EmnapiError)) { + var setPrototypeOf = Object.setPrototypeOf; + if (typeof setPrototypeOf === 'function') { + setPrototypeOf.call(Object, _this, proto); + } + else { + // eslint-disable-next-line no-proto + _this.__proto__ = proto; + } + if (typeof Error.captureStackTrace === 'function') { + Error.captureStackTrace(_this, ErrorConstructor); + } + } + return _this; + } + return EmnapiError; + }(Error)); + Object.defineProperty(EmnapiError.prototype, 'name', { + configurable: true, + writable: true, + value: 'EmnapiError' + }); + var NotSupportWeakRefError = /*#__PURE__*/ (function (_super) { + __extends(NotSupportWeakRefError, _super); + function NotSupportWeakRefError(api, message) { + return _super.call(this, "".concat(api, ": The current runtime does not support \"FinalizationRegistry\" and \"WeakRef\".").concat(message ? " ".concat(message) : '')) || this; + } + return NotSupportWeakRefError; + }(EmnapiError)); + Object.defineProperty(NotSupportWeakRefError.prototype, 'name', { + configurable: true, + writable: true, + value: 'NotSupportWeakRefError' + }); + var NotSupportBufferError = /*#__PURE__*/ (function (_super) { + __extends(NotSupportBufferError, _super); + function NotSupportBufferError(api, message) { + return _super.call(this, "".concat(api, ": The current runtime does not support \"Buffer\". Consider using buffer polyfill to make sure `globalThis.Buffer` is defined.").concat(message ? " ".concat(message) : '')) || this; + } + return NotSupportBufferError; + }(EmnapiError)); + Object.defineProperty(NotSupportBufferError.prototype, 'name', { + configurable: true, + writable: true, + value: 'NotSupportBufferError' + }); + + var StrongRef = /*#__PURE__*/ (function () { + function StrongRef(value) { + this._value = value; + } + StrongRef.prototype.deref = function () { + return this._value; + }; + StrongRef.prototype.dispose = function () { + this._value = undefined; + }; + return StrongRef; + }()); + var Persistent = /*#__PURE__*/ (function () { + function Persistent(value) { + this._ref = new StrongRef(value); + } + Persistent.prototype.setWeak = function (param, callback) { + if (!supportFinalizer || this._ref === undefined || this._ref instanceof WeakRef) + return; + var value = this._ref.deref(); + try { + Persistent._registry.register(value, this, this); + var weakRef = new WeakRef(value); + this._ref.dispose(); + this._ref = weakRef; + this._param = param; + this._callback = callback; + } + catch (err) { + if (typeof value === 'symbol') ; + else { + throw err; + } + } + }; + Persistent.prototype.clearWeak = function () { + if (!supportFinalizer || this._ref === undefined) + return; + if (this._ref instanceof WeakRef) { + try { + Persistent._registry.unregister(this); + } + catch (_) { } + this._param = undefined; + this._callback = undefined; + var value = this._ref.deref(); + if (value === undefined) { + this._ref = value; + } + else { + this._ref = new StrongRef(value); + } + } + }; + Persistent.prototype.reset = function () { + if (supportFinalizer) { + try { + Persistent._registry.unregister(this); + } + catch (_) { } + } + this._param = undefined; + this._callback = undefined; + if (this._ref instanceof StrongRef) { + this._ref.dispose(); + } + this._ref = undefined; + }; + Persistent.prototype.isEmpty = function () { + return this._ref === undefined; + }; + Persistent.prototype.deref = function () { + if (this._ref === undefined) + return undefined; + return this._ref.deref(); + }; + Persistent._registry = supportFinalizer + ? new FinalizationRegistry(function (value) { + value._ref = undefined; + var callback = value._callback; + var param = value._param; + value._callback = undefined; + value._param = undefined; + if (typeof callback === 'function') { + callback(param); + } + }) + : undefined; + return Persistent; + }()); + + exports.ReferenceOwnership = void 0; + (function (ReferenceOwnership) { + ReferenceOwnership[ReferenceOwnership["kRuntime"] = 0] = "kRuntime"; + ReferenceOwnership[ReferenceOwnership["kUserland"] = 1] = "kUserland"; + })(exports.ReferenceOwnership || (exports.ReferenceOwnership = {})); + function canBeHeldWeakly(value) { + return value.isObject() || value.isFunction() || value.isSymbol(); + } + var Reference = /*#__PURE__*/ (function (_super) { + __extends(Reference, _super); + function Reference(envObject, handle_id, initialRefcount, ownership) { + var _this = _super.call(this) || this; + _this.envObject = envObject; + _this._refcount = initialRefcount; + _this._ownership = ownership; + var handle = envObject.ctx.handleStore.get(handle_id); + _this.canBeWeak = canBeHeldWeakly(handle); + _this.persistent = new Persistent(handle.value); + _this.id = 0; + if (initialRefcount === 0) { + _this._setWeak(); + } + return _this; + } + Reference.weakCallback = function (ref) { + ref.persistent.reset(); + ref.invokeFinalizerFromGC(); + }; + Reference.create = function (envObject, handle_id, initialRefcount, ownership, _unused1, _unused2, _unused3) { + var ref = new Reference(envObject, handle_id, initialRefcount, ownership); + envObject.ctx.refStore.add(ref); + ref.link(envObject.reflist); + return ref; + }; + Reference.prototype.ref = function () { + if (this.persistent.isEmpty()) { + return 0; + } + if (++this._refcount === 1 && this.canBeWeak) { + this.persistent.clearWeak(); + } + return this._refcount; + }; + Reference.prototype.unref = function () { + if (this.persistent.isEmpty() || this._refcount === 0) { + return 0; + } + if (--this._refcount === 0) { + this._setWeak(); + } + return this._refcount; + }; + Reference.prototype.get = function (envObject) { + if (envObject === void 0) { envObject = this.envObject; } + if (this.persistent.isEmpty()) { + return 0; + } + var obj = this.persistent.deref(); + var handle = envObject.ensureHandle(obj); + return handle.id; + }; + /** @virtual */ + Reference.prototype.resetFinalizer = function () { }; + /** @virtual */ + Reference.prototype.data = function () { return 0; }; + Reference.prototype.refcount = function () { return this._refcount; }; + Reference.prototype.ownership = function () { return this._ownership; }; + /** @virtual */ + Reference.prototype.callUserFinalizer = function () { }; + /** @virtual */ + Reference.prototype.invokeFinalizerFromGC = function () { + this.finalize(); + }; + Reference.prototype._setWeak = function () { + if (this.canBeWeak) { + this.persistent.setWeak(this, Reference.weakCallback); + } + else { + this.persistent.reset(); + } + }; + Reference.prototype.finalize = function () { + this.persistent.reset(); + var deleteMe = this._ownership === exports.ReferenceOwnership.kRuntime; + this.unlink(); + this.callUserFinalizer(); + if (deleteMe) { + this.dispose(); + } + }; + Reference.prototype.dispose = function () { + if (this.id === 0) + return; + this.unlink(); + this.persistent.reset(); + this.envObject.ctx.refStore.remove(this.id); + _super.prototype.dispose.call(this); + this.envObject = undefined; + this.id = 0; + }; + return Reference; + }(RefTracker)); + var ReferenceWithData = /*#__PURE__*/ (function (_super) { + __extends(ReferenceWithData, _super); + function ReferenceWithData(envObject, value, initialRefcount, ownership, _data) { + var _this = _super.call(this, envObject, value, initialRefcount, ownership) || this; + _this._data = _data; + return _this; + } + ReferenceWithData.create = function (envObject, value, initialRefcount, ownership, data) { + var reference = new ReferenceWithData(envObject, value, initialRefcount, ownership, data); + envObject.ctx.refStore.add(reference); + reference.link(envObject.reflist); + return reference; + }; + ReferenceWithData.prototype.data = function () { + return this._data; + }; + return ReferenceWithData; + }(Reference)); + var ReferenceWithFinalizer = /*#__PURE__*/ (function (_super) { + __extends(ReferenceWithFinalizer, _super); + function ReferenceWithFinalizer(envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint) { + var _this = _super.call(this, envObject, value, initialRefcount, ownership) || this; + _this._finalizer = new Finalizer(envObject, finalize_callback, finalize_data, finalize_hint); + return _this; + } + ReferenceWithFinalizer.create = function (envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint) { + var reference = new ReferenceWithFinalizer(envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint); + envObject.ctx.refStore.add(reference); + reference.link(envObject.finalizing_reflist); + return reference; + }; + ReferenceWithFinalizer.prototype.resetFinalizer = function () { + this._finalizer.resetFinalizer(); + }; + ReferenceWithFinalizer.prototype.data = function () { + return this._finalizer.data(); + }; + ReferenceWithFinalizer.prototype.callUserFinalizer = function () { + this._finalizer.callFinalizer(); + }; + ReferenceWithFinalizer.prototype.invokeFinalizerFromGC = function () { + this._finalizer.envObject.invokeFinalizerFromGC(this); + }; + ReferenceWithFinalizer.prototype.dispose = function () { + if (!this._finalizer) + return; + this._finalizer.envObject.dequeueFinalizer(this); + this._finalizer.dispose(); + _super.prototype.dispose.call(this); + this._finalizer = undefined; + }; + return ReferenceWithFinalizer; + }(Reference)); + + var Deferred = /*#__PURE__*/ (function () { + function Deferred(ctx, value) { + // Plain assignment would invoke inherited setters before these fields + // become own properties. + Object.defineProperties(this, { + id: { + configurable: true, + enumerable: true, + value: 0, + writable: true + }, + ctx: { + configurable: true, + enumerable: true, + value: ctx, + writable: true + }, + value: { + configurable: true, + enumerable: true, + value: value, + writable: true + } + }); + } + Deferred.create = function (ctx, value) { + var deferred = new Deferred(ctx, value); + ctx.deferredStore.add(deferred); + return deferred; + }; + Deferred.prototype.resolve = function (value) { + this.value.resolve(value); + this.dispose(); + }; + Deferred.prototype.reject = function (reason) { + this.value.reject(reason); + this.dispose(); + }; + Deferred.prototype.dispose = function () { + this.ctx.deferredStore.remove(this.id); + this.id = 0; + this.value = null; + this.ctx = null; + }; + return Deferred; + }()); + + var Store = /*#__PURE__*/ (function () { + function Store() { + this._values = [undefined]; + this._values.length = 4; + this._size = 1; + this._freeList = []; + } + Store.prototype.add = function (value) { + var id; + if (this._freeList.length) { + id = this._freeList.shift(); + } + else { + id = this._size; + this._size++; + var capacity = this._values.length; + if (id >= capacity) { + this._values.length = capacity + (capacity >> 1) + 16; + } + } + value.id = id; + this._values[id] = value; + }; + Store.prototype.get = function (id) { + return this._values[id]; + }; + Store.prototype.has = function (id) { + return this._values[id] !== undefined; + }; + Store.prototype.remove = function (id) { + var value = this._values[id]; + if (value) { + value.id = 0; + this._values[id] = undefined; + this._freeList.push(Number(id)); + } + }; + Store.prototype.dispose = function () { + for (var i = 1; i < this._size; ++i) { + var value = this._values[i]; + value === null || value === void 0 ? void 0 : value.dispose(); + } + this._values = [undefined]; + this._size = 1; + this._freeList = []; + }; + return Store; + }()); + + var kMaxReasonableBytes = BigInt(1) << BigInt(60); + var kMinReasonableBytes = -kMaxReasonableBytes; + var ExternalMemory = /*#__PURE__*/ (function () { + function ExternalMemory(onChange) { + this.total = BigInt(0); + this.onChange = onChange !== null && onChange !== void 0 ? onChange : null; + } + ExternalMemory.prototype.adjust = function (changeInBytes) { + changeInBytes = BigInt(changeInBytes); + if (!(kMinReasonableBytes <= changeInBytes && changeInBytes < kMaxReasonableBytes)) { + throw new RangeError("changeInBytes ".concat(changeInBytes, " is out of reasonable range")); + } + var old = this.total; + this.total += changeInBytes; + var amount = this.total; + var onChange = this.onChange; + if (changeInBytes) { + onChange === null || onChange === void 0 ? void 0 : onChange(amount, old, changeInBytes); + } + return amount; + }; + return ExternalMemory; + }()); + + var CleanupHookCallback = /*#__PURE__*/ (function () { + function CleanupHookCallback(envObject, fn, arg, order) { + this.envObject = envObject; + this.fn = fn; + this.arg = arg; + this.order = order; + } + return CleanupHookCallback; + }()); + var CleanupQueue = /*#__PURE__*/ (function () { + function CleanupQueue() { + this._cleanupHooks = []; + this._cleanupHookCounter = 0; + } + CleanupQueue.prototype.empty = function () { + return this._cleanupHooks.length === 0; + }; + CleanupQueue.prototype.add = function (envObject, fn, arg) { + if (this._cleanupHooks.filter(function (hook) { return (hook.envObject === envObject && hook.fn === fn && hook.arg === arg); }).length > 0) { + throw new Error('Can not add same fn and arg twice'); + } + this._cleanupHooks.push(new CleanupHookCallback(envObject, fn, arg, this._cleanupHookCounter++)); + }; + CleanupQueue.prototype.remove = function (envObject, fn, arg) { + for (var i = 0; i < this._cleanupHooks.length; ++i) { + var hook = this._cleanupHooks[i]; + if (hook.envObject === envObject && hook.fn === fn && hook.arg === arg) { + this._cleanupHooks.splice(i, 1); + return; + } + } + }; + CleanupQueue.prototype.drain = function () { + var hooks = this._cleanupHooks.slice(); + hooks.sort(function (a, b) { return (b.order - a.order); }); + for (var i = 0; i < hooks.length; ++i) { + var cb = hooks[i]; + if (typeof cb.fn === 'number') { + cb.envObject.makeDynCall_vp(cb.fn)(cb.arg); + } + else { + cb.fn(cb.arg); + } + this._cleanupHooks.splice(this._cleanupHooks.indexOf(cb), 1); + } + }; + CleanupQueue.prototype.dispose = function () { + this._cleanupHooks.length = 0; + this._cleanupHookCounter = 0; + }; + return CleanupQueue; + }()); + var NodejsWaitingRequestCounter = /*#__PURE__*/ (function () { + function NodejsWaitingRequestCounter() { + this.refHandle = new _MessageChannel().port1; + this.count = 0; + } + NodejsWaitingRequestCounter.prototype.increase = function () { + if (this.count === 0) { + if (this.refHandle.ref) { + this.refHandle.ref(); + } + } + this.count++; + }; + NodejsWaitingRequestCounter.prototype.decrease = function () { + if (this.count === 0) + return; + if (this.count === 1) { + if (this.refHandle.unref) { + this.refHandle.unref(); + } + } + this.count--; + }; + return NodejsWaitingRequestCounter; + }()); + var Context = /*#__PURE__*/ (function () { + function Context(options) { + var _this = this; + this._isStopping = false; + this._canCallIntoJs = true; + this._suppressDestroy = false; + this.envStore = new Store(); + this.scopeStore = new ScopeStore(); + this.refStore = new Store(); + this.deferredStore = new Store(); + this.handleStore = new HandleStore(); + this.feature = { + supportReflect: supportReflect, + supportFinalizer: supportFinalizer, + supportWeakSymbol: supportWeakSymbol, + supportBigInt: supportBigInt, + supportNewFunction: supportNewFunction, + canSetFunctionName: canSetFunctionName, + setImmediate: _setImmediate, + Buffer: _Buffer, + MessageChannel: _MessageChannel + }; + this.cleanupQueue = new CleanupQueue(); + this._externalMemory = new ExternalMemory(options === null || options === void 0 ? void 0 : options.onExternalMemoryChange); + if (typeof process === 'object' && process !== null && typeof process.once === 'function') { + this.refCounter = new NodejsWaitingRequestCounter(); + process.once('beforeExit', function () { + if (!_this._suppressDestroy) { + _this.destroy(); + } + }); + } + } + /** + * Suppress the destroy on `beforeExit` event in Node.js. + * Call this method if you want to keep the context and + * all associated {@link Env | Env} alive, + * this also means that cleanup hooks will not be called. + * After call this method, you should call + * {@link Context.destroy | `Context.prototype.destroy`} method manually. + */ + Context.prototype.suppressDestroy = function () { + this._suppressDestroy = true; + }; + // eslint-disable-next-line @typescript-eslint/explicit-function-return-type + Context.prototype.getRuntimeVersions = function () { + return { + version: version, + NODE_API_SUPPORTED_VERSION_MAX: NODE_API_SUPPORTED_VERSION_MAX, + NAPI_VERSION_EXPERIMENTAL: NAPI_VERSION_EXPERIMENTAL, + NODE_API_DEFAULT_MODULE_API_VERSION: NODE_API_DEFAULT_MODULE_API_VERSION + }; + }; + Context.prototype.createNotSupportWeakRefError = function (api, message) { + return new NotSupportWeakRefError(api, message); + }; + Context.prototype.createNotSupportBufferError = function (api, message) { + return new NotSupportBufferError(api, message); + }; + Context.prototype.createReference = function (envObject, handle_id, initialRefcount, ownership) { + return Reference.create(envObject, handle_id, initialRefcount, ownership); + }; + Context.prototype.createReferenceWithData = function (envObject, handle_id, initialRefcount, ownership, data) { + return ReferenceWithData.create(envObject, handle_id, initialRefcount, ownership, data); + }; + Context.prototype.createReferenceWithFinalizer = function (envObject, handle_id, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint) { + if (finalize_callback === void 0) { finalize_callback = 0; } + if (finalize_data === void 0) { finalize_data = 0; } + if (finalize_hint === void 0) { finalize_hint = 0; } + return ReferenceWithFinalizer.create(envObject, handle_id, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint); + }; + Context.prototype.createDeferred = function (value) { + return Deferred.create(this, value); + }; + Context.prototype.adjustAmountOfExternalAllocatedMemory = function (changeInBytes) { + return this._externalMemory.adjust(changeInBytes); + }; + Context.prototype.createEnv = function (filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding) { + return newEnv(this, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding); + }; + Context.prototype.createTrackedFinalizer = function (envObject, finalize_callback, finalize_data, finalize_hint) { + return TrackedFinalizer.create(envObject, finalize_callback, finalize_data, finalize_hint); + }; + Context.prototype.getCurrentScope = function () { + return this.scopeStore.currentScope; + }; + Context.prototype.addToCurrentScope = function (value) { + return this.scopeStore.currentScope.add(value); + }; + Context.prototype.openScope = function (envObject) { + var scope = this.scopeStore.openScope(this.handleStore); + if (envObject) + envObject.openHandleScopes++; + return scope; + }; + Context.prototype.closeScope = function (envObject, _scope) { + if (envObject && envObject.openHandleScopes === 0) + return; + this.scopeStore.closeScope(); + if (envObject) + envObject.openHandleScopes--; + }; + Context.prototype.ensureHandle = function (value) { + switch (value) { + case undefined: return HandleStore.UNDEFINED; + case null: return HandleStore.NULL; + case true: return HandleStore.TRUE; + case false: return HandleStore.FALSE; + case _global: return HandleStore.GLOBAL; + } + return this.addToCurrentScope(value); + }; + Context.prototype.addCleanupHook = function (envObject, fn, arg) { + this.cleanupQueue.add(envObject, fn, arg); + }; + Context.prototype.removeCleanupHook = function (envObject, fn, arg) { + this.cleanupQueue.remove(envObject, fn, arg); + }; + Context.prototype.runCleanup = function () { + while (!this.cleanupQueue.empty()) { + this.cleanupQueue.drain(); + } + }; + Context.prototype.increaseWaitingRequestCounter = function () { + var _a; + (_a = this.refCounter) === null || _a === void 0 ? void 0 : _a.increase(); + }; + Context.prototype.decreaseWaitingRequestCounter = function () { + var _a; + (_a = this.refCounter) === null || _a === void 0 ? void 0 : _a.decrease(); + }; + Context.prototype.setCanCallIntoJs = function (value) { + this._canCallIntoJs = value; + }; + Context.prototype.setStopping = function (value) { + this._isStopping = value; + }; + Context.prototype.canCallIntoJs = function () { + return this._canCallIntoJs && !this._isStopping; + }; + /** + * Destroy the context and call cleanup hooks. + * Associated {@link Env | Env} will be destroyed. + */ + Context.prototype.destroy = function () { + this.setStopping(true); + this.setCanCallIntoJs(false); + this.runCleanup(); + }; + return Context; + }()); + var defaultContext; + function createContext(options) { + return new Context(options); + } + function getDefaultContext() { + if (!defaultContext) { + defaultContext = createContext(); + } + return defaultContext; + } + + exports.ConstHandle = ConstHandle; + exports.Context = Context; + exports.Deferred = Deferred; + exports.EmnapiError = EmnapiError; + exports.Env = Env; + exports.External = External; + exports.Finalizer = Finalizer; + exports.Handle = Handle; + exports.HandleScope = HandleScope; + exports.HandleStore = HandleStore; + exports.NAPI_VERSION_EXPERIMENTAL = NAPI_VERSION_EXPERIMENTAL; + exports.NODE_API_DEFAULT_MODULE_API_VERSION = NODE_API_DEFAULT_MODULE_API_VERSION; + exports.NODE_API_SUPPORTED_VERSION_MAX = NODE_API_SUPPORTED_VERSION_MAX; + exports.NODE_API_SUPPORTED_VERSION_MIN = NODE_API_SUPPORTED_VERSION_MIN; + exports.NodeEnv = NodeEnv; + exports.NotSupportBufferError = NotSupportBufferError; + exports.NotSupportWeakRefError = NotSupportWeakRefError; + exports.Persistent = Persistent; + exports.RefTracker = RefTracker; + exports.Reference = Reference; + exports.ReferenceWithData = ReferenceWithData; + exports.ReferenceWithFinalizer = ReferenceWithFinalizer; + exports.ScopeStore = ScopeStore; + exports.Store = Store; + exports.TrackedFinalizer = TrackedFinalizer; + exports.TryCatch = TryCatch; + exports.createContext = createContext; + exports.getDefaultContext = getDefaultContext; + exports.getExternalValue = getExternalValue; + exports.isExternal = isExternal; + exports.isReferenceType = isReferenceType; + exports.version = version; + + return exports; + +})({}); diff --git a/node_modules/@emnapi/runtime/dist/emnapi.js b/node_modules/@emnapi/runtime/dist/emnapi.js new file mode 100644 index 0000000..e7af366 --- /dev/null +++ b/node_modules/@emnapi/runtime/dist/emnapi.js @@ -0,0 +1,1529 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.emnapi = {})); +})(this, (function (exports) { + /****************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise, SuppressedError, Symbol, Iterator */ + + var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + + function __extends(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; + }; + + var externalValue = new WeakMap(); + /** @public */ + function isExternal(object) { + return externalValue.has(object); + } + /** @public */ // eslint-disable-next-line @typescript-eslint/no-redeclare + var External = (function () { + function External(value) { + Object.setPrototypeOf(this, null); + externalValue.set(this, value); + } + External.prototype = null; + return External; + })(); + /** @public */ + function getExternalValue(external) { + if (!isExternal(external)) { + throw new TypeError('not external'); + } + return externalValue.get(external); + } + + var supportNewFunction = /*#__PURE__*/ (function () { + var f; + try { + f = new Function(); + } + catch (_) { + return false; + } + return typeof f === 'function'; + })(); + var _global = /*#__PURE__*/ (function () { + if (typeof globalThis !== 'undefined') + return globalThis; + var g = (function () { return this; })(); + if (!g && supportNewFunction) { + try { + g = new Function('return this')(); + } + catch (_) { } + } + if (!g) { + if (typeof __webpack_public_path__ === 'undefined') { + if (typeof global !== 'undefined') + return global; + } + if (typeof window !== 'undefined') + return window; + if (typeof self !== 'undefined') + return self; + } + return g; + })(); + var TryCatch = /*#__PURE__*/ (function () { + function TryCatch() { + this._exception = undefined; + this._caught = false; + } + TryCatch.prototype.isEmpty = function () { + return !this._caught; + }; + TryCatch.prototype.hasCaught = function () { + return this._caught; + }; + TryCatch.prototype.exception = function () { + return this._exception; + }; + TryCatch.prototype.setError = function (err) { + this._caught = true; + this._exception = err; + }; + TryCatch.prototype.reset = function () { + this._caught = false; + this._exception = undefined; + }; + TryCatch.prototype.extractException = function () { + var e = this._exception; + this.reset(); + return e; + }; + return TryCatch; + }()); + var canSetFunctionName = /*#__PURE__*/ (function () { + var _a; + try { + return Boolean((_a = Object.getOwnPropertyDescriptor(Function.prototype, 'name')) === null || _a === void 0 ? void 0 : _a.configurable); + } + catch (_) { + return false; + } + })(); + var supportReflect = typeof Reflect === 'object'; + var supportFinalizer = (typeof FinalizationRegistry !== 'undefined') && (typeof WeakRef !== 'undefined'); + var supportWeakSymbol = /*#__PURE__*/ (function () { + try { + // eslint-disable-next-line symbol-description + var sym = Symbol(); + // eslint-disable-next-line no-new + new WeakRef(sym); + new WeakMap().set(sym, undefined); + } + catch (_) { + return false; + } + return true; + })(); + var supportBigInt = typeof BigInt !== 'undefined'; + function isReferenceType(v) { + return (typeof v === 'object' && v !== null) || typeof v === 'function'; + } + var _require = /*#__PURE__*/ (function () { + var nativeRequire; + if (typeof __webpack_public_path__ !== 'undefined') { + nativeRequire = (function () { + return typeof __non_webpack_require__ !== 'undefined' ? __non_webpack_require__ : undefined; + })(); + } + else { + nativeRequire = (function () { + return typeof __webpack_public_path__ !== 'undefined' ? (typeof __non_webpack_require__ !== 'undefined' ? __non_webpack_require__ : undefined) : (typeof require !== 'undefined' ? require : undefined); + })(); + } + return nativeRequire; + })(); + var _MessageChannel = typeof MessageChannel === 'function' + ? MessageChannel + : /*#__PURE__*/ (function () { + try { + return _require('worker_threads').MessageChannel; + } + catch (_) { } + return undefined; + })(); + var _setImmediate = typeof setImmediate === 'function' + ? setImmediate.bind(_global) + : function (callback) { + if (typeof callback !== 'function') { + throw new TypeError('The "callback" argument must be of type function'); + } + if (_MessageChannel) { + var channel_1 = new _MessageChannel(); + channel_1.port1.onmessage = function () { + channel_1.port1.onmessage = null; + channel_1 = undefined; + callback(); + }; + channel_1.port2.postMessage(null); + } + else { + setTimeout(callback, 0); + } + }; + var _Buffer = typeof Buffer === 'function' + ? Buffer + : /*#__PURE__*/ (function () { + try { + return _require('buffer').Buffer; + } + catch (_) { } + return undefined; + })(); + var version = "1.11.3"; + var NODE_API_SUPPORTED_VERSION_MIN = 1 /* Version.NODE_API_SUPPORTED_VERSION_MIN */; + var NODE_API_SUPPORTED_VERSION_MAX = 10 /* Version.NODE_API_SUPPORTED_VERSION_MAX */; + var NAPI_VERSION_EXPERIMENTAL = 2147483647 /* Version.NAPI_VERSION_EXPERIMENTAL */; + var NODE_API_DEFAULT_MODULE_API_VERSION = 8 /* Version.NODE_API_DEFAULT_MODULE_API_VERSION */; + + var Handle = /*#__PURE__*/ (function () { + function Handle(id, value) { + this.id = id; + this.value = value; + } + Handle.prototype.data = function () { + return getExternalValue(this.value); + }; + Handle.prototype.isNumber = function () { + return typeof this.value === 'number'; + }; + Handle.prototype.isBigInt = function () { + return typeof this.value === 'bigint'; + }; + Handle.prototype.isString = function () { + return typeof this.value === 'string'; + }; + Handle.prototype.isFunction = function () { + return typeof this.value === 'function'; + }; + Handle.prototype.isExternal = function () { + return isExternal(this.value); + }; + Handle.prototype.isObject = function () { + return typeof this.value === 'object' && this.value !== null; + }; + Handle.prototype.isArray = function () { + return Array.isArray(this.value); + }; + Handle.prototype.isArrayBuffer = function () { + return (this.value instanceof ArrayBuffer); + }; + Handle.prototype.isTypedArray = function () { + return (ArrayBuffer.isView(this.value)) && !(this.value instanceof DataView); + }; + Handle.prototype.isBuffer = function (BufferConstructor) { + if (ArrayBuffer.isView(this.value)) + return true; + BufferConstructor !== null && BufferConstructor !== void 0 ? BufferConstructor : (BufferConstructor = _Buffer); + return typeof BufferConstructor === 'function' && BufferConstructor.isBuffer(this.value); + }; + Handle.prototype.isDataView = function () { + return (this.value instanceof DataView); + }; + Handle.prototype.isDate = function () { + return (this.value instanceof Date); + }; + Handle.prototype.isPromise = function () { + return (this.value instanceof Promise); + }; + Handle.prototype.isBoolean = function () { + return typeof this.value === 'boolean'; + }; + Handle.prototype.isUndefined = function () { + return this.value === undefined; + }; + Handle.prototype.isSymbol = function () { + return typeof this.value === 'symbol'; + }; + Handle.prototype.isNull = function () { + return this.value === null; + }; + Handle.prototype.dispose = function () { + this.value = undefined; + }; + return Handle; + }()); + var ConstHandle = /*#__PURE__*/ (function (_super) { + __extends(ConstHandle, _super); + function ConstHandle(id, value) { + return _super.call(this, id, value) || this; + } + ConstHandle.prototype.dispose = function () { }; + return ConstHandle; + }(Handle)); + var HandleStore = /*#__PURE__*/ (function () { + function HandleStore() { + this._values = [ + undefined, + HandleStore.UNDEFINED, + HandleStore.NULL, + HandleStore.FALSE, + HandleStore.TRUE, + HandleStore.GLOBAL + ]; + this._next = HandleStore.MIN_ID; + } + HandleStore.prototype.push = function (value) { + var h; + var next = this._next; + var values = this._values; + if (next < values.length) { + h = values[next]; + h.value = value; + } + else { + h = new Handle(next, value); + values[next] = h; + } + this._next++; + return h; + }; + HandleStore.prototype.erase = function (start, end) { + this._next = start; + var values = this._values; + for (var i = start; i < end; ++i) { + values[i].dispose(); + } + }; + HandleStore.prototype.get = function (id) { + return this._values[id]; + }; + HandleStore.prototype.swap = function (a, b) { + var values = this._values; + var h = values[a]; + values[a] = values[b]; + values[a].id = Number(a); + values[b] = h; + h.id = Number(b); + }; + HandleStore.prototype.dispose = function () { + this._values.length = HandleStore.MIN_ID; + this._next = HandleStore.MIN_ID; + }; + HandleStore.UNDEFINED = new ConstHandle(1 /* GlobalHandle.UNDEFINED */, undefined); + HandleStore.NULL = new ConstHandle(2 /* GlobalHandle.NULL */, null); + HandleStore.FALSE = new ConstHandle(3 /* GlobalHandle.FALSE */, false); + HandleStore.TRUE = new ConstHandle(4 /* GlobalHandle.TRUE */, true); + HandleStore.GLOBAL = new ConstHandle(5 /* GlobalHandle.GLOBAL */, _global); + HandleStore.MIN_ID = 6; + return HandleStore; + }()); + + var HandleScope = /*#__PURE__*/ (function () { + function HandleScope(handleStore, id, parentScope, start, end) { + if (end === void 0) { end = start; } + this.handleStore = handleStore; + this.id = id; + this.parent = parentScope; + this.child = null; + if (parentScope !== null) + parentScope.child = this; + this.start = start; + this.end = end; + this._escapeCalled = false; + this.callbackInfo = { + thiz: undefined, + data: 0, + args: undefined, + fn: undefined + }; + } + HandleScope.prototype.add = function (value) { + var h = this.handleStore.push(value); + this.end++; + return h; + }; + HandleScope.prototype.addExternal = function (data) { + return this.add(new External(data)); + }; + HandleScope.prototype.dispose = function () { + if (this._escapeCalled) + this._escapeCalled = false; + if (this.start === this.end) + return; + this.handleStore.erase(this.start, this.end); + }; + HandleScope.prototype.escape = function (handle) { + if (this._escapeCalled) + return null; + this._escapeCalled = true; + if (handle < this.start || handle >= this.end) { + return null; + } + this.handleStore.swap(handle, this.start); + var h = this.handleStore.get(this.start); + this.start++; + this.parent.end++; + return h; + }; + HandleScope.prototype.escapeCalled = function () { + return this._escapeCalled; + }; + return HandleScope; + }()); + + var ScopeStore = /*#__PURE__*/ (function () { + function ScopeStore() { + this._rootScope = new HandleScope(null, 0, null, 1, HandleStore.MIN_ID); + this.currentScope = this._rootScope; + this._values = [undefined]; + } + ScopeStore.prototype.get = function (id) { + return this._values[id]; + }; + ScopeStore.prototype.openScope = function (handleStore) { + var currentScope = this.currentScope; + var scope = currentScope.child; + if (scope !== null) { + scope.start = scope.end = currentScope.end; + } + else { + var id = currentScope.id + 1; + scope = new HandleScope(handleStore, id, currentScope, currentScope.end); + this._values[id] = scope; + } + this.currentScope = scope; + return scope; + }; + ScopeStore.prototype.closeScope = function () { + var scope = this.currentScope; + this.currentScope = scope.parent; + scope.dispose(); + }; + ScopeStore.prototype.dispose = function () { + this.currentScope = this._rootScope; + this._values.length = 1; + }; + return ScopeStore; + }()); + + var RefTracker = /*#__PURE__*/ (function () { + function RefTracker() { + this._next = null; + this._prev = null; + } + /** @virtual */ + RefTracker.prototype.dispose = function () { }; + /** @virtual */ + RefTracker.prototype.finalize = function () { }; + RefTracker.prototype.link = function (list) { + this._prev = list; + this._next = list._next; + if (this._next !== null) { + this._next._prev = this; + } + list._next = this; + }; + RefTracker.prototype.unlink = function () { + if (this._prev !== null) { + this._prev._next = this._next; + } + if (this._next !== null) { + this._next._prev = this._prev; + } + this._prev = null; + this._next = null; + }; + RefTracker.finalizeAll = function (list) { + while (list._next !== null) { + list._next.finalize(); + } + }; + return RefTracker; + }()); + + var Finalizer = /*#__PURE__*/ (function () { + function Finalizer(envObject, _finalizeCallback, _finalizeData, _finalizeHint) { + if (_finalizeCallback === void 0) { _finalizeCallback = 0; } + if (_finalizeData === void 0) { _finalizeData = 0; } + if (_finalizeHint === void 0) { _finalizeHint = 0; } + this.envObject = envObject; + this._finalizeCallback = _finalizeCallback; + this._finalizeData = _finalizeData; + this._finalizeHint = _finalizeHint; + this._makeDynCall_vppp = envObject.makeDynCall_vppp; + } + Finalizer.prototype.callback = function () { return this._finalizeCallback; }; + Finalizer.prototype.data = function () { return this._finalizeData; }; + Finalizer.prototype.hint = function () { return this._finalizeHint; }; + Finalizer.prototype.resetEnv = function () { + this.envObject = undefined; + }; + Finalizer.prototype.resetFinalizer = function () { + this._finalizeCallback = 0; + this._finalizeData = 0; + this._finalizeHint = 0; + }; + Finalizer.prototype.callFinalizer = function () { + var finalize_callback = this._finalizeCallback; + var finalize_data = this._finalizeData; + var finalize_hint = this._finalizeHint; + this.resetFinalizer(); + if (!finalize_callback) + return; + var fini = Number(finalize_callback); + if (!this.envObject) { + this._makeDynCall_vppp(fini)(0, finalize_data, finalize_hint); + } + else { + this.envObject.callFinalizer(fini, finalize_data, finalize_hint); + } + }; + Finalizer.prototype.dispose = function () { + this.envObject = undefined; + this._makeDynCall_vppp = undefined; + }; + return Finalizer; + }()); + + var TrackedFinalizer = /*#__PURE__*/ (function (_super) { + __extends(TrackedFinalizer, _super); + function TrackedFinalizer(envObject, finalize_callback, finalize_data, finalize_hint) { + var _this = _super.call(this) || this; + _this._finalizer = new Finalizer(envObject, finalize_callback, finalize_data, finalize_hint); + return _this; + } + TrackedFinalizer.create = function (envObject, finalize_callback, finalize_data, finalize_hint) { + var finalizer = new TrackedFinalizer(envObject, finalize_callback, finalize_data, finalize_hint); + finalizer.link(envObject.finalizing_reflist); + return finalizer; + }; + TrackedFinalizer.prototype.data = function () { + return this._finalizer.data(); + }; + TrackedFinalizer.prototype.dispose = function () { + if (!this._finalizer) + return; + this.unlink(); + this._finalizer.envObject.dequeueFinalizer(this); + this._finalizer.dispose(); + this._finalizer = undefined; + _super.prototype.dispose.call(this); + }; + TrackedFinalizer.prototype.finalize = function () { + this.unlink(); + var error; + var caught = false; + try { + this._finalizer.callFinalizer(); + } + catch (err) { + caught = true; + error = err; + } + this.dispose(); + if (caught) { + throw error; + } + }; + return TrackedFinalizer; + }(RefTracker)); + + function throwNodeApiVersionError(moduleName, moduleApiVersion) { + var errorMessage = "".concat(moduleName, " requires Node-API version ").concat(moduleApiVersion, ", but this version of Node.js only supports version ").concat(NODE_API_SUPPORTED_VERSION_MAX, " add-ons."); + throw new Error(errorMessage); + } + function handleThrow(envObject, value) { + if (envObject.terminatedOrTerminating()) { + return; + } + throw value; + } + var Env = /*#__PURE__*/ (function () { + function Env(ctx, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort) { + this.ctx = ctx; + this.moduleApiVersion = moduleApiVersion; + this.makeDynCall_vppp = makeDynCall_vppp; + this.makeDynCall_vp = makeDynCall_vp; + this.abort = abort; + this.openHandleScopes = 0; + this.instanceData = null; + this.tryCatch = new TryCatch(); + this.refs = 1; + this.reflist = new RefTracker(); + this.finalizing_reflist = new RefTracker(); + this.pendingFinalizers = []; + this.lastError = { + errorCode: 0 /* napi_status.napi_ok */, + engineErrorCode: 0, + engineReserved: 0 + }; + this.inGcFinalizer = false; + this._bindingMap = new WeakMap(); + this.id = 0; + } + /** @virtual */ + Env.prototype.canCallIntoJs = function () { + return true; + }; + Env.prototype.terminatedOrTerminating = function () { + return !this.canCallIntoJs(); + }; + Env.prototype.ref = function () { + this.refs++; + }; + Env.prototype.unref = function () { + this.refs--; + if (this.refs === 0) { + this.dispose(); + } + }; + Env.prototype.ensureHandle = function (value) { + return this.ctx.ensureHandle(value); + }; + Env.prototype.ensureHandleId = function (value) { + return this.ensureHandle(value).id; + }; + Env.prototype.clearLastError = function () { + var lastError = this.lastError; + if (lastError.errorCode !== 0 /* napi_status.napi_ok */) + lastError.errorCode = 0 /* napi_status.napi_ok */; + if (lastError.engineErrorCode !== 0) + lastError.engineErrorCode = 0; + if (lastError.engineReserved !== 0) + lastError.engineReserved = 0; + return 0 /* napi_status.napi_ok */; + }; + Env.prototype.setLastError = function (error_code, engine_error_code, engine_reserved) { + if (engine_error_code === void 0) { engine_error_code = 0; } + if (engine_reserved === void 0) { engine_reserved = 0; } + var lastError = this.lastError; + if (lastError.errorCode !== error_code) + lastError.errorCode = error_code; + if (lastError.engineErrorCode !== engine_error_code) + lastError.engineErrorCode = engine_error_code; + if (lastError.engineReserved !== engine_reserved) + lastError.engineReserved = engine_reserved; + return error_code; + }; + Env.prototype.getReturnStatus = function () { + return !this.tryCatch.hasCaught() ? 0 /* napi_status.napi_ok */ : this.setLastError(10 /* napi_status.napi_pending_exception */); + }; + Env.prototype.callIntoModule = function (fn, handleException) { + if (handleException === void 0) { handleException = handleThrow; } + var openHandleScopesBefore = this.openHandleScopes; + this.clearLastError(); + var r = fn(this); + if (openHandleScopesBefore !== this.openHandleScopes) { + this.abort('open_handle_scopes != open_handle_scopes_before'); + } + if (this.tryCatch.hasCaught()) { + var err = this.tryCatch.extractException(); + handleException(this, err); + } + return r; + }; + Env.prototype.invokeFinalizerFromGC = function (finalizer) { + if (this.moduleApiVersion !== NAPI_VERSION_EXPERIMENTAL) { + this.enqueueFinalizer(finalizer); + } + else { + var saved = this.inGcFinalizer; + this.inGcFinalizer = true; + try { + finalizer.finalize(); + } + finally { + this.inGcFinalizer = saved; + } + } + }; + Env.prototype.checkGCAccess = function () { + if (this.moduleApiVersion === NAPI_VERSION_EXPERIMENTAL && this.inGcFinalizer) { + this.abort('Finalizer is calling a function that may affect GC state.\n' + + 'The finalizers are run directly from GC and must not affect GC ' + + 'state.\n' + + 'Use `node_api_post_finalizer` from inside of the finalizer to work ' + + 'around this issue.\n' + + 'It schedules the call as a new task in the event loop.'); + } + }; + /** @virtual */ + Env.prototype.enqueueFinalizer = function (finalizer) { + if (this.pendingFinalizers.indexOf(finalizer) === -1) { + this.pendingFinalizers.push(finalizer); + } + }; + /** @virtual */ + Env.prototype.dequeueFinalizer = function (finalizer) { + var index = this.pendingFinalizers.indexOf(finalizer); + if (index !== -1) { + this.pendingFinalizers.splice(index, 1); + } + }; + /** @virtual */ + Env.prototype.deleteMe = function () { + RefTracker.finalizeAll(this.finalizing_reflist); + RefTracker.finalizeAll(this.reflist); + this.tryCatch.extractException(); + this.ctx.envStore.remove(this.id); + }; + Env.prototype.dispose = function () { + if (this.id === 0) + return; + this.deleteMe(); + this.finalizing_reflist.dispose(); + this.reflist.dispose(); + this.id = 0; + }; + Env.prototype.initObjectBinding = function (value) { + var binding = { + wrapped: 0, + tag: null + }; + this._bindingMap.set(value, binding); + return binding; + }; + Env.prototype.getObjectBinding = function (value) { + if (this._bindingMap.has(value)) { + return this._bindingMap.get(value); + } + return this.initObjectBinding(value); + }; + Env.prototype.setInstanceData = function (data, finalize_cb, finalize_hint) { + if (this.instanceData) { + this.instanceData.dispose(); + } + this.instanceData = TrackedFinalizer.create(this, finalize_cb, data, finalize_hint); + }; + Env.prototype.getInstanceData = function () { + return this.instanceData ? this.instanceData.data() : 0; + }; + return Env; + }()); + var NodeEnv = /*#__PURE__*/ (function (_super) { + __extends(NodeEnv, _super); + function NodeEnv(ctx, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding) { + var _this = _super.call(this, ctx, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort) || this; + _this.filename = filename; + _this.nodeBinding = nodeBinding; + _this.destructing = false; + _this.finalizationScheduled = false; + return _this; + } + NodeEnv.prototype.deleteMe = function () { + this.destructing = true; + this.drainFinalizerQueue(); + _super.prototype.deleteMe.call(this); + }; + NodeEnv.prototype.canCallIntoJs = function () { + return _super.prototype.canCallIntoJs.call(this) && this.ctx.canCallIntoJs(); + }; + NodeEnv.prototype.triggerFatalException = function (err) { + if (this.nodeBinding) { + this.nodeBinding.napi.fatalException(err); + } + else { + if (typeof process === 'object' && process !== null && typeof process._fatalException === 'function') { + var handled = process._fatalException(err); + if (!handled) { + console.error(err); + process.exit(1); + } + } + else { + throw err; + } + } + }; + NodeEnv.prototype.callbackIntoModule = function (enforceUncaughtExceptionPolicy, fn) { + return this.callIntoModule(fn, function (envObject, err) { + if (envObject.terminatedOrTerminating()) { + return; + } + var hasProcess = typeof process === 'object' && process !== null; + var hasForceFlag = hasProcess ? Boolean(process.execArgv && (process.execArgv.indexOf('--force-node-api-uncaught-exceptions-policy') !== -1)) : false; + if (envObject.moduleApiVersion < 10 && !hasForceFlag && !enforceUncaughtExceptionPolicy) { + var warn = hasProcess && typeof process.emitWarning === 'function' + ? process.emitWarning + : function (warning, type, code) { + if (warning instanceof Error) { + console.warn(warning.toString()); + } + else { + var prefix = code ? "[".concat(code, "] ") : ''; + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + console.warn("".concat(prefix).concat(type || 'Warning', ": ").concat(warning)); + } + }; + warn('Uncaught Node-API callback exception detected, please run node with option --force-node-api-uncaught-exceptions-policy=true to handle those exceptions properly.', 'DeprecationWarning', 'DEP0168'); + return; + } + envObject.triggerFatalException(err); + }); + }; + NodeEnv.prototype.callFinalizer = function (cb, data, hint) { + this.callFinalizerInternal(1, cb, data, hint); + }; + NodeEnv.prototype.callFinalizerInternal = function (forceUncaught, cb, data, hint) { + var f = this.makeDynCall_vppp(cb); + var env = this.id; + var scope = this.ctx.openScope(this); + try { + this.callbackIntoModule(Boolean(forceUncaught), function () { f(env, data, hint); }); + } + finally { + this.ctx.closeScope(this, scope); + } + }; + NodeEnv.prototype.enqueueFinalizer = function (finalizer) { + var _this = this; + _super.prototype.enqueueFinalizer.call(this, finalizer); + if (!this.finalizationScheduled && !this.destructing) { + this.finalizationScheduled = true; + this.ref(); + _setImmediate(function () { + _this.finalizationScheduled = false; + _this.unref(); + _this.drainFinalizerQueue(); + }); + } + }; + NodeEnv.prototype.drainFinalizerQueue = function () { + while (this.pendingFinalizers.length > 0) { + var refTracker = this.pendingFinalizers.shift(); + refTracker.finalize(); + } + }; + return NodeEnv; + }(Env)); + function newEnv(ctx, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding) { + moduleApiVersion = typeof moduleApiVersion !== 'number' ? NODE_API_DEFAULT_MODULE_API_VERSION : moduleApiVersion; + // Validate module_api_version. + if (moduleApiVersion < NODE_API_DEFAULT_MODULE_API_VERSION) { + moduleApiVersion = NODE_API_DEFAULT_MODULE_API_VERSION; + } + else if (moduleApiVersion > NODE_API_SUPPORTED_VERSION_MAX && moduleApiVersion !== NAPI_VERSION_EXPERIMENTAL) { + throwNodeApiVersionError(filename, moduleApiVersion); + } + var env = new NodeEnv(ctx, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding); + ctx.envStore.add(env); + ctx.addCleanupHook(env, function () { env.unref(); }, 0); + return env; + } + + var EmnapiError = /*#__PURE__*/ (function (_super) { + __extends(EmnapiError, _super); + function EmnapiError(message) { + var _newTarget = this.constructor; + var _this = _super.call(this, message) || this; + var ErrorConstructor = _newTarget; + var proto = ErrorConstructor.prototype; + if (!(_this instanceof EmnapiError)) { + var setPrototypeOf = Object.setPrototypeOf; + if (typeof setPrototypeOf === 'function') { + setPrototypeOf.call(Object, _this, proto); + } + else { + // eslint-disable-next-line no-proto + _this.__proto__ = proto; + } + if (typeof Error.captureStackTrace === 'function') { + Error.captureStackTrace(_this, ErrorConstructor); + } + } + return _this; + } + return EmnapiError; + }(Error)); + Object.defineProperty(EmnapiError.prototype, 'name', { + configurable: true, + writable: true, + value: 'EmnapiError' + }); + var NotSupportWeakRefError = /*#__PURE__*/ (function (_super) { + __extends(NotSupportWeakRefError, _super); + function NotSupportWeakRefError(api, message) { + return _super.call(this, "".concat(api, ": The current runtime does not support \"FinalizationRegistry\" and \"WeakRef\".").concat(message ? " ".concat(message) : '')) || this; + } + return NotSupportWeakRefError; + }(EmnapiError)); + Object.defineProperty(NotSupportWeakRefError.prototype, 'name', { + configurable: true, + writable: true, + value: 'NotSupportWeakRefError' + }); + var NotSupportBufferError = /*#__PURE__*/ (function (_super) { + __extends(NotSupportBufferError, _super); + function NotSupportBufferError(api, message) { + return _super.call(this, "".concat(api, ": The current runtime does not support \"Buffer\". Consider using buffer polyfill to make sure `globalThis.Buffer` is defined.").concat(message ? " ".concat(message) : '')) || this; + } + return NotSupportBufferError; + }(EmnapiError)); + Object.defineProperty(NotSupportBufferError.prototype, 'name', { + configurable: true, + writable: true, + value: 'NotSupportBufferError' + }); + + var StrongRef = /*#__PURE__*/ (function () { + function StrongRef(value) { + this._value = value; + } + StrongRef.prototype.deref = function () { + return this._value; + }; + StrongRef.prototype.dispose = function () { + this._value = undefined; + }; + return StrongRef; + }()); + var Persistent = /*#__PURE__*/ (function () { + function Persistent(value) { + this._ref = new StrongRef(value); + } + Persistent.prototype.setWeak = function (param, callback) { + if (!supportFinalizer || this._ref === undefined || this._ref instanceof WeakRef) + return; + var value = this._ref.deref(); + try { + Persistent._registry.register(value, this, this); + var weakRef = new WeakRef(value); + this._ref.dispose(); + this._ref = weakRef; + this._param = param; + this._callback = callback; + } + catch (err) { + if (typeof value === 'symbol') ; + else { + throw err; + } + } + }; + Persistent.prototype.clearWeak = function () { + if (!supportFinalizer || this._ref === undefined) + return; + if (this._ref instanceof WeakRef) { + try { + Persistent._registry.unregister(this); + } + catch (_) { } + this._param = undefined; + this._callback = undefined; + var value = this._ref.deref(); + if (value === undefined) { + this._ref = value; + } + else { + this._ref = new StrongRef(value); + } + } + }; + Persistent.prototype.reset = function () { + if (supportFinalizer) { + try { + Persistent._registry.unregister(this); + } + catch (_) { } + } + this._param = undefined; + this._callback = undefined; + if (this._ref instanceof StrongRef) { + this._ref.dispose(); + } + this._ref = undefined; + }; + Persistent.prototype.isEmpty = function () { + return this._ref === undefined; + }; + Persistent.prototype.deref = function () { + if (this._ref === undefined) + return undefined; + return this._ref.deref(); + }; + Persistent._registry = supportFinalizer + ? new FinalizationRegistry(function (value) { + value._ref = undefined; + var callback = value._callback; + var param = value._param; + value._callback = undefined; + value._param = undefined; + if (typeof callback === 'function') { + callback(param); + } + }) + : undefined; + return Persistent; + }()); + + exports.ReferenceOwnership = void 0; + (function (ReferenceOwnership) { + ReferenceOwnership[ReferenceOwnership["kRuntime"] = 0] = "kRuntime"; + ReferenceOwnership[ReferenceOwnership["kUserland"] = 1] = "kUserland"; + })(exports.ReferenceOwnership || (exports.ReferenceOwnership = {})); + function canBeHeldWeakly(value) { + return value.isObject() || value.isFunction() || value.isSymbol(); + } + var Reference = /*#__PURE__*/ (function (_super) { + __extends(Reference, _super); + function Reference(envObject, handle_id, initialRefcount, ownership) { + var _this = _super.call(this) || this; + _this.envObject = envObject; + _this._refcount = initialRefcount; + _this._ownership = ownership; + var handle = envObject.ctx.handleStore.get(handle_id); + _this.canBeWeak = canBeHeldWeakly(handle); + _this.persistent = new Persistent(handle.value); + _this.id = 0; + if (initialRefcount === 0) { + _this._setWeak(); + } + return _this; + } + Reference.weakCallback = function (ref) { + ref.persistent.reset(); + ref.invokeFinalizerFromGC(); + }; + Reference.create = function (envObject, handle_id, initialRefcount, ownership, _unused1, _unused2, _unused3) { + var ref = new Reference(envObject, handle_id, initialRefcount, ownership); + envObject.ctx.refStore.add(ref); + ref.link(envObject.reflist); + return ref; + }; + Reference.prototype.ref = function () { + if (this.persistent.isEmpty()) { + return 0; + } + if (++this._refcount === 1 && this.canBeWeak) { + this.persistent.clearWeak(); + } + return this._refcount; + }; + Reference.prototype.unref = function () { + if (this.persistent.isEmpty() || this._refcount === 0) { + return 0; + } + if (--this._refcount === 0) { + this._setWeak(); + } + return this._refcount; + }; + Reference.prototype.get = function (envObject) { + if (envObject === void 0) { envObject = this.envObject; } + if (this.persistent.isEmpty()) { + return 0; + } + var obj = this.persistent.deref(); + var handle = envObject.ensureHandle(obj); + return handle.id; + }; + /** @virtual */ + Reference.prototype.resetFinalizer = function () { }; + /** @virtual */ + Reference.prototype.data = function () { return 0; }; + Reference.prototype.refcount = function () { return this._refcount; }; + Reference.prototype.ownership = function () { return this._ownership; }; + /** @virtual */ + Reference.prototype.callUserFinalizer = function () { }; + /** @virtual */ + Reference.prototype.invokeFinalizerFromGC = function () { + this.finalize(); + }; + Reference.prototype._setWeak = function () { + if (this.canBeWeak) { + this.persistent.setWeak(this, Reference.weakCallback); + } + else { + this.persistent.reset(); + } + }; + Reference.prototype.finalize = function () { + this.persistent.reset(); + var deleteMe = this._ownership === exports.ReferenceOwnership.kRuntime; + this.unlink(); + this.callUserFinalizer(); + if (deleteMe) { + this.dispose(); + } + }; + Reference.prototype.dispose = function () { + if (this.id === 0) + return; + this.unlink(); + this.persistent.reset(); + this.envObject.ctx.refStore.remove(this.id); + _super.prototype.dispose.call(this); + this.envObject = undefined; + this.id = 0; + }; + return Reference; + }(RefTracker)); + var ReferenceWithData = /*#__PURE__*/ (function (_super) { + __extends(ReferenceWithData, _super); + function ReferenceWithData(envObject, value, initialRefcount, ownership, _data) { + var _this = _super.call(this, envObject, value, initialRefcount, ownership) || this; + _this._data = _data; + return _this; + } + ReferenceWithData.create = function (envObject, value, initialRefcount, ownership, data) { + var reference = new ReferenceWithData(envObject, value, initialRefcount, ownership, data); + envObject.ctx.refStore.add(reference); + reference.link(envObject.reflist); + return reference; + }; + ReferenceWithData.prototype.data = function () { + return this._data; + }; + return ReferenceWithData; + }(Reference)); + var ReferenceWithFinalizer = /*#__PURE__*/ (function (_super) { + __extends(ReferenceWithFinalizer, _super); + function ReferenceWithFinalizer(envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint) { + var _this = _super.call(this, envObject, value, initialRefcount, ownership) || this; + _this._finalizer = new Finalizer(envObject, finalize_callback, finalize_data, finalize_hint); + return _this; + } + ReferenceWithFinalizer.create = function (envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint) { + var reference = new ReferenceWithFinalizer(envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint); + envObject.ctx.refStore.add(reference); + reference.link(envObject.finalizing_reflist); + return reference; + }; + ReferenceWithFinalizer.prototype.resetFinalizer = function () { + this._finalizer.resetFinalizer(); + }; + ReferenceWithFinalizer.prototype.data = function () { + return this._finalizer.data(); + }; + ReferenceWithFinalizer.prototype.callUserFinalizer = function () { + this._finalizer.callFinalizer(); + }; + ReferenceWithFinalizer.prototype.invokeFinalizerFromGC = function () { + this._finalizer.envObject.invokeFinalizerFromGC(this); + }; + ReferenceWithFinalizer.prototype.dispose = function () { + if (!this._finalizer) + return; + this._finalizer.envObject.dequeueFinalizer(this); + this._finalizer.dispose(); + _super.prototype.dispose.call(this); + this._finalizer = undefined; + }; + return ReferenceWithFinalizer; + }(Reference)); + + var Deferred = /*#__PURE__*/ (function () { + function Deferred(ctx, value) { + // Plain assignment would invoke inherited setters before these fields + // become own properties. + Object.defineProperties(this, { + id: { + configurable: true, + enumerable: true, + value: 0, + writable: true + }, + ctx: { + configurable: true, + enumerable: true, + value: ctx, + writable: true + }, + value: { + configurable: true, + enumerable: true, + value: value, + writable: true + } + }); + } + Deferred.create = function (ctx, value) { + var deferred = new Deferred(ctx, value); + ctx.deferredStore.add(deferred); + return deferred; + }; + Deferred.prototype.resolve = function (value) { + this.value.resolve(value); + this.dispose(); + }; + Deferred.prototype.reject = function (reason) { + this.value.reject(reason); + this.dispose(); + }; + Deferred.prototype.dispose = function () { + this.ctx.deferredStore.remove(this.id); + this.id = 0; + this.value = null; + this.ctx = null; + }; + return Deferred; + }()); + + var Store = /*#__PURE__*/ (function () { + function Store() { + this._values = [undefined]; + this._values.length = 4; + this._size = 1; + this._freeList = []; + } + Store.prototype.add = function (value) { + var id; + if (this._freeList.length) { + id = this._freeList.shift(); + } + else { + id = this._size; + this._size++; + var capacity = this._values.length; + if (id >= capacity) { + this._values.length = capacity + (capacity >> 1) + 16; + } + } + value.id = id; + this._values[id] = value; + }; + Store.prototype.get = function (id) { + return this._values[id]; + }; + Store.prototype.has = function (id) { + return this._values[id] !== undefined; + }; + Store.prototype.remove = function (id) { + var value = this._values[id]; + if (value) { + value.id = 0; + this._values[id] = undefined; + this._freeList.push(Number(id)); + } + }; + Store.prototype.dispose = function () { + for (var i = 1; i < this._size; ++i) { + var value = this._values[i]; + value === null || value === void 0 ? void 0 : value.dispose(); + } + this._values = [undefined]; + this._size = 1; + this._freeList = []; + }; + return Store; + }()); + + var kMaxReasonableBytes = BigInt(1) << BigInt(60); + var kMinReasonableBytes = -kMaxReasonableBytes; + var ExternalMemory = /*#__PURE__*/ (function () { + function ExternalMemory(onChange) { + this.total = BigInt(0); + this.onChange = onChange !== null && onChange !== void 0 ? onChange : null; + } + ExternalMemory.prototype.adjust = function (changeInBytes) { + changeInBytes = BigInt(changeInBytes); + if (!(kMinReasonableBytes <= changeInBytes && changeInBytes < kMaxReasonableBytes)) { + throw new RangeError("changeInBytes ".concat(changeInBytes, " is out of reasonable range")); + } + var old = this.total; + this.total += changeInBytes; + var amount = this.total; + var onChange = this.onChange; + if (changeInBytes) { + onChange === null || onChange === void 0 ? void 0 : onChange(amount, old, changeInBytes); + } + return amount; + }; + return ExternalMemory; + }()); + + var CleanupHookCallback = /*#__PURE__*/ (function () { + function CleanupHookCallback(envObject, fn, arg, order) { + this.envObject = envObject; + this.fn = fn; + this.arg = arg; + this.order = order; + } + return CleanupHookCallback; + }()); + var CleanupQueue = /*#__PURE__*/ (function () { + function CleanupQueue() { + this._cleanupHooks = []; + this._cleanupHookCounter = 0; + } + CleanupQueue.prototype.empty = function () { + return this._cleanupHooks.length === 0; + }; + CleanupQueue.prototype.add = function (envObject, fn, arg) { + if (this._cleanupHooks.filter(function (hook) { return (hook.envObject === envObject && hook.fn === fn && hook.arg === arg); }).length > 0) { + throw new Error('Can not add same fn and arg twice'); + } + this._cleanupHooks.push(new CleanupHookCallback(envObject, fn, arg, this._cleanupHookCounter++)); + }; + CleanupQueue.prototype.remove = function (envObject, fn, arg) { + for (var i = 0; i < this._cleanupHooks.length; ++i) { + var hook = this._cleanupHooks[i]; + if (hook.envObject === envObject && hook.fn === fn && hook.arg === arg) { + this._cleanupHooks.splice(i, 1); + return; + } + } + }; + CleanupQueue.prototype.drain = function () { + var hooks = this._cleanupHooks.slice(); + hooks.sort(function (a, b) { return (b.order - a.order); }); + for (var i = 0; i < hooks.length; ++i) { + var cb = hooks[i]; + if (typeof cb.fn === 'number') { + cb.envObject.makeDynCall_vp(cb.fn)(cb.arg); + } + else { + cb.fn(cb.arg); + } + this._cleanupHooks.splice(this._cleanupHooks.indexOf(cb), 1); + } + }; + CleanupQueue.prototype.dispose = function () { + this._cleanupHooks.length = 0; + this._cleanupHookCounter = 0; + }; + return CleanupQueue; + }()); + var NodejsWaitingRequestCounter = /*#__PURE__*/ (function () { + function NodejsWaitingRequestCounter() { + this.refHandle = new _MessageChannel().port1; + this.count = 0; + } + NodejsWaitingRequestCounter.prototype.increase = function () { + if (this.count === 0) { + if (this.refHandle.ref) { + this.refHandle.ref(); + } + } + this.count++; + }; + NodejsWaitingRequestCounter.prototype.decrease = function () { + if (this.count === 0) + return; + if (this.count === 1) { + if (this.refHandle.unref) { + this.refHandle.unref(); + } + } + this.count--; + }; + return NodejsWaitingRequestCounter; + }()); + var Context = /*#__PURE__*/ (function () { + function Context(options) { + var _this = this; + this._isStopping = false; + this._canCallIntoJs = true; + this._suppressDestroy = false; + this.envStore = new Store(); + this.scopeStore = new ScopeStore(); + this.refStore = new Store(); + this.deferredStore = new Store(); + this.handleStore = new HandleStore(); + this.feature = { + supportReflect: supportReflect, + supportFinalizer: supportFinalizer, + supportWeakSymbol: supportWeakSymbol, + supportBigInt: supportBigInt, + supportNewFunction: supportNewFunction, + canSetFunctionName: canSetFunctionName, + setImmediate: _setImmediate, + Buffer: _Buffer, + MessageChannel: _MessageChannel + }; + this.cleanupQueue = new CleanupQueue(); + this._externalMemory = new ExternalMemory(options === null || options === void 0 ? void 0 : options.onExternalMemoryChange); + if (typeof process === 'object' && process !== null && typeof process.once === 'function') { + this.refCounter = new NodejsWaitingRequestCounter(); + process.once('beforeExit', function () { + if (!_this._suppressDestroy) { + _this.destroy(); + } + }); + } + } + /** + * Suppress the destroy on `beforeExit` event in Node.js. + * Call this method if you want to keep the context and + * all associated {@link Env | Env} alive, + * this also means that cleanup hooks will not be called. + * After call this method, you should call + * {@link Context.destroy | `Context.prototype.destroy`} method manually. + */ + Context.prototype.suppressDestroy = function () { + this._suppressDestroy = true; + }; + // eslint-disable-next-line @typescript-eslint/explicit-function-return-type + Context.prototype.getRuntimeVersions = function () { + return { + version: version, + NODE_API_SUPPORTED_VERSION_MAX: NODE_API_SUPPORTED_VERSION_MAX, + NAPI_VERSION_EXPERIMENTAL: NAPI_VERSION_EXPERIMENTAL, + NODE_API_DEFAULT_MODULE_API_VERSION: NODE_API_DEFAULT_MODULE_API_VERSION + }; + }; + Context.prototype.createNotSupportWeakRefError = function (api, message) { + return new NotSupportWeakRefError(api, message); + }; + Context.prototype.createNotSupportBufferError = function (api, message) { + return new NotSupportBufferError(api, message); + }; + Context.prototype.createReference = function (envObject, handle_id, initialRefcount, ownership) { + return Reference.create(envObject, handle_id, initialRefcount, ownership); + }; + Context.prototype.createReferenceWithData = function (envObject, handle_id, initialRefcount, ownership, data) { + return ReferenceWithData.create(envObject, handle_id, initialRefcount, ownership, data); + }; + Context.prototype.createReferenceWithFinalizer = function (envObject, handle_id, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint) { + if (finalize_callback === void 0) { finalize_callback = 0; } + if (finalize_data === void 0) { finalize_data = 0; } + if (finalize_hint === void 0) { finalize_hint = 0; } + return ReferenceWithFinalizer.create(envObject, handle_id, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint); + }; + Context.prototype.createDeferred = function (value) { + return Deferred.create(this, value); + }; + Context.prototype.adjustAmountOfExternalAllocatedMemory = function (changeInBytes) { + return this._externalMemory.adjust(changeInBytes); + }; + Context.prototype.createEnv = function (filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding) { + return newEnv(this, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding); + }; + Context.prototype.createTrackedFinalizer = function (envObject, finalize_callback, finalize_data, finalize_hint) { + return TrackedFinalizer.create(envObject, finalize_callback, finalize_data, finalize_hint); + }; + Context.prototype.getCurrentScope = function () { + return this.scopeStore.currentScope; + }; + Context.prototype.addToCurrentScope = function (value) { + return this.scopeStore.currentScope.add(value); + }; + Context.prototype.openScope = function (envObject) { + var scope = this.scopeStore.openScope(this.handleStore); + if (envObject) + envObject.openHandleScopes++; + return scope; + }; + Context.prototype.closeScope = function (envObject, _scope) { + if (envObject && envObject.openHandleScopes === 0) + return; + this.scopeStore.closeScope(); + if (envObject) + envObject.openHandleScopes--; + }; + Context.prototype.ensureHandle = function (value) { + switch (value) { + case undefined: return HandleStore.UNDEFINED; + case null: return HandleStore.NULL; + case true: return HandleStore.TRUE; + case false: return HandleStore.FALSE; + case _global: return HandleStore.GLOBAL; + } + return this.addToCurrentScope(value); + }; + Context.prototype.addCleanupHook = function (envObject, fn, arg) { + this.cleanupQueue.add(envObject, fn, arg); + }; + Context.prototype.removeCleanupHook = function (envObject, fn, arg) { + this.cleanupQueue.remove(envObject, fn, arg); + }; + Context.prototype.runCleanup = function () { + while (!this.cleanupQueue.empty()) { + this.cleanupQueue.drain(); + } + }; + Context.prototype.increaseWaitingRequestCounter = function () { + var _a; + (_a = this.refCounter) === null || _a === void 0 ? void 0 : _a.increase(); + }; + Context.prototype.decreaseWaitingRequestCounter = function () { + var _a; + (_a = this.refCounter) === null || _a === void 0 ? void 0 : _a.decrease(); + }; + Context.prototype.setCanCallIntoJs = function (value) { + this._canCallIntoJs = value; + }; + Context.prototype.setStopping = function (value) { + this._isStopping = value; + }; + Context.prototype.canCallIntoJs = function () { + return this._canCallIntoJs && !this._isStopping; + }; + /** + * Destroy the context and call cleanup hooks. + * Associated {@link Env | Env} will be destroyed. + */ + Context.prototype.destroy = function () { + this.setStopping(true); + this.setCanCallIntoJs(false); + this.runCleanup(); + }; + return Context; + }()); + var defaultContext; + function createContext(options) { + return new Context(options); + } + function getDefaultContext() { + if (!defaultContext) { + defaultContext = createContext(); + } + return defaultContext; + } + + exports.ConstHandle = ConstHandle; + exports.Context = Context; + exports.Deferred = Deferred; + exports.EmnapiError = EmnapiError; + exports.Env = Env; + exports.External = External; + exports.Finalizer = Finalizer; + exports.Handle = Handle; + exports.HandleScope = HandleScope; + exports.HandleStore = HandleStore; + exports.NAPI_VERSION_EXPERIMENTAL = NAPI_VERSION_EXPERIMENTAL; + exports.NODE_API_DEFAULT_MODULE_API_VERSION = NODE_API_DEFAULT_MODULE_API_VERSION; + exports.NODE_API_SUPPORTED_VERSION_MAX = NODE_API_SUPPORTED_VERSION_MAX; + exports.NODE_API_SUPPORTED_VERSION_MIN = NODE_API_SUPPORTED_VERSION_MIN; + exports.NodeEnv = NodeEnv; + exports.NotSupportBufferError = NotSupportBufferError; + exports.NotSupportWeakRefError = NotSupportWeakRefError; + exports.Persistent = Persistent; + exports.RefTracker = RefTracker; + exports.Reference = Reference; + exports.ReferenceWithData = ReferenceWithData; + exports.ReferenceWithFinalizer = ReferenceWithFinalizer; + exports.ScopeStore = ScopeStore; + exports.Store = Store; + exports.TrackedFinalizer = TrackedFinalizer; + exports.TryCatch = TryCatch; + exports.createContext = createContext; + exports.getDefaultContext = getDefaultContext; + exports.getExternalValue = getExternalValue; + exports.isExternal = isExternal; + exports.isReferenceType = isReferenceType; + exports.version = version; + +})); diff --git a/node_modules/@emnapi/runtime/dist/emnapi.min.d.mts b/node_modules/@emnapi/runtime/dist/emnapi.min.d.mts new file mode 100644 index 0000000..c2404e3 --- /dev/null +++ b/node_modules/@emnapi/runtime/dist/emnapi.min.d.mts @@ -0,0 +1,671 @@ +export declare type Ptr = number | bigint + +export declare interface IBuffer extends Uint8Array {} +export declare interface BufferCtor { + readonly prototype: IBuffer + /** @deprecated */ + new (...args: any[]): IBuffer + from: { + (buffer: ArrayBufferLike): IBuffer + (buffer: ArrayBufferLike, byteOffset: number, length: number): IBuffer + } + alloc: (size: number) => IBuffer + isBuffer: (obj: unknown) => obj is IBuffer +} + +export declare const enum GlobalHandle { + UNDEFINED = 1, + NULL, + FALSE, + TRUE, + GLOBAL +} + +export declare const enum Version { + NODE_API_SUPPORTED_VERSION_MIN = 1, + NODE_API_DEFAULT_MODULE_API_VERSION = 8, + NODE_API_SUPPORTED_VERSION_MAX = 10, + NAPI_VERSION_EXPERIMENTAL = 2147483647 // INT_MAX +} +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export declare type Pointer = number +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export declare type PointerPointer = number +export declare type FunctionPointer any> = Pointer +export declare type Const = T + +export declare type void_p = Pointer +export declare type void_pp = Pointer +export declare type bool = number +export declare type char = number +export declare type char_p = Pointer +export declare type unsigned_char = number +export declare type const_char = Const +export declare type const_char_p = Pointer +export declare type char16_t_p = number +export declare type const_char16_t_p = number + +export declare type short = number +export declare type unsigned_short = number +export declare type int = number +export declare type unsigned_int = number +export declare type long = number +export declare type unsigned_long = number +export declare type long_long = bigint +export declare type unsigned_long_long = bigint +export declare type float = number +export declare type double = number +export declare type long_double = number +export declare type size_t = number + +export declare type int8_t = number +export declare type uint8_t = number +export declare type int16_t = number +export declare type uint16_t = number +export declare type int32_t = number +export declare type uint32_t = number +export declare type int64_t = bigint +export declare type uint64_t = bigint +export declare type napi_env = Pointer + +export declare type napi_value = Pointer +export declare type napi_ref = Pointer +export declare type napi_deferred = Pointer +export declare type napi_handle_scope = Pointer +export declare type napi_escapable_handle_scope = Pointer + +export declare type napi_addon_register_func = FunctionPointer<(env: napi_env, exports: napi_value) => napi_value> + +export declare type napi_callback_info = Pointer +export declare type napi_callback = FunctionPointer<(env: napi_env, info: napi_callback_info) => napi_value> + +export declare interface napi_extended_error_info { + error_message: const_char_p + engine_reserved: void_p + engine_error_code: uint32_t + error_code: napi_status +} + +export declare interface napi_property_descriptor { + // One of utf8name or name should be NULL. + utf8name: const_char_p + name: napi_value + + method: napi_callback + getter: napi_callback + setter: napi_callback + value: napi_value + /* napi_property_attributes */ + attributes: number + data: void_p +} + +export declare type napi_finalize = FunctionPointer<( + env: napi_env, + finalize_data: void_p, + finalize_hint: void_p +) => void> + +export declare interface node_module { + nm_version: int32_t + nm_flags: uint32_t + nm_filename: Pointer + nm_register_func: napi_addon_register_func + nm_modname: Pointer + nm_priv: Pointer + reserved: PointerPointer +} + +export declare interface napi_node_version { + major: uint32_t + minor: uint32_t + patch: uint32_t + release: const_char_p +} + +export declare interface emnapi_emscripten_version { + major: uint32_t + minor: uint32_t + patch: uint32_t +} + +export declare const enum napi_status { + napi_ok, + napi_invalid_arg, + napi_object_expected, + napi_string_expected, + napi_name_expected, + napi_function_expected, + napi_number_expected, + napi_boolean_expected, + napi_array_expected, + napi_generic_failure, + napi_pending_exception, + napi_cancelled, + napi_escape_called_twice, + napi_handle_scope_mismatch, + napi_callback_scope_mismatch, + napi_queue_full, + napi_closing, + napi_bigint_expected, + napi_date_expected, + napi_arraybuffer_expected, + napi_detachable_arraybuffer_expected, + napi_would_deadlock, // unused + napi_no_external_buffers_allowed, + napi_cannot_run_js +} + +export declare const enum napi_property_attributes { + napi_default = 0, + napi_writable = 1 << 0, + napi_enumerable = 1 << 1, + napi_configurable = 1 << 2, + + // Used with napi_define_class to distinguish static properties + // from instance properties. Ignored by napi_define_properties. + napi_static = 1 << 10, + + /// #ifdef NAPI_EXPERIMENTAL + // Default for class methods. + napi_default_method = napi_writable | napi_configurable, + + // Default for object properties, like in JS obj[prop]. + napi_default_jsproperty = napi_writable | napi_enumerable | napi_configurable + /// #endif // NAPI_EXPERIMENTAL +} + +export declare const enum napi_valuetype { + napi_undefined, + napi_null, + napi_boolean, + napi_number, + napi_string, + napi_symbol, + napi_object, + napi_function, + napi_external, + napi_bigint +} + +export declare const enum napi_typedarray_type { + napi_int8_array, + napi_uint8_array, + napi_uint8_clamped_array, + napi_int16_array, + napi_uint16_array, + napi_int32_array, + napi_uint32_array, + napi_float32_array, + napi_float64_array, + napi_bigint64_array, + napi_biguint64_array, + napi_float16_array, +} + +export declare const enum napi_key_collection_mode { + napi_key_include_prototypes, + napi_key_own_only +} + +export declare const enum napi_key_filter { + napi_key_all_properties = 0, + napi_key_writable = 1, + napi_key_enumerable = 1 << 1, + napi_key_configurable = 1 << 2, + napi_key_skip_strings = 1 << 3, + napi_key_skip_symbols = 1 << 4 +} + +export declare const enum napi_key_conversion { + napi_key_keep_numbers, + napi_key_numbers_to_strings +} + +export declare const enum emnapi_memory_view_type { + emnapi_int8_array, + emnapi_uint8_array, + emnapi_uint8_clamped_array, + emnapi_int16_array, + emnapi_uint16_array, + emnapi_int32_array, + emnapi_uint32_array, + emnapi_float32_array, + emnapi_float64_array, + emnapi_bigint64_array, + emnapi_biguint64_array, + emnapi_float16_array, + emnapi_data_view = -1, + emnapi_buffer = -2 +} + +export declare const enum napi_threadsafe_function_call_mode { + napi_tsfn_nonblocking, + napi_tsfn_blocking +} + +export declare const enum napi_threadsafe_function_release_mode { + napi_tsfn_release, + napi_tsfn_abort +} +export declare type CleanupHookCallbackFunction = number | ((arg: number) => void); + +export declare class ConstHandle extends Handle { + constructor(id: number, value: S); + dispose(): void; +} + +export declare class Context { + private _isStopping; + private _canCallIntoJs; + private _suppressDestroy; + envStore: Store; + scopeStore: ScopeStore; + refStore: Store; + deferredStore: Store>; + handleStore: HandleStore; + private readonly refCounter?; + private readonly cleanupQueue; + private readonly _externalMemory; + feature: { + supportReflect: boolean; + supportFinalizer: boolean; + supportWeakSymbol: boolean; + supportBigInt: boolean; + supportNewFunction: boolean; + canSetFunctionName: boolean; + setImmediate: (callback: () => void) => void; + Buffer: BufferCtor | undefined; + MessageChannel: { + new (): MessageChannel; + prototype: MessageChannel; + } | undefined; + }; + constructor(options?: ContextOptions); + /** + * Suppress the destroy on `beforeExit` event in Node.js. + * Call this method if you want to keep the context and + * all associated {@link Env | Env} alive, + * this also means that cleanup hooks will not be called. + * After call this method, you should call + * {@link Context.destroy | `Context.prototype.destroy`} method manually. + */ + suppressDestroy(): void; + getRuntimeVersions(): { + version: string; + NODE_API_SUPPORTED_VERSION_MAX: Version; + NAPI_VERSION_EXPERIMENTAL: Version; + NODE_API_DEFAULT_MODULE_API_VERSION: Version; + }; + createNotSupportWeakRefError(api: string, message: string): NotSupportWeakRefError; + createNotSupportBufferError(api: string, message: string): NotSupportBufferError; + createReference(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership): Reference; + createReferenceWithData(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, data: void_p): Reference; + createReferenceWithFinalizer(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, finalize_callback?: napi_finalize, finalize_data?: void_p, finalize_hint?: void_p): Reference; + createDeferred(value: IDeferrdValue): Deferred; + adjustAmountOfExternalAllocatedMemory(changeInBytes: number | bigint): bigint; + createEnv(filename: string, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never, nodeBinding?: any): Env; + createTrackedFinalizer(envObject: Env, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): TrackedFinalizer; + getCurrentScope(): HandleScope | null; + addToCurrentScope(value: V): Handle; + openScope(envObject?: Env): HandleScope; + closeScope(envObject?: Env, _scope?: HandleScope): void; + ensureHandle(value: S): Handle; + addCleanupHook(envObject: Env, fn: CleanupHookCallbackFunction, arg: number): void; + removeCleanupHook(envObject: Env, fn: CleanupHookCallbackFunction, arg: number): void; + runCleanup(): void; + increaseWaitingRequestCounter(): void; + decreaseWaitingRequestCounter(): void; + setCanCallIntoJs(value: boolean): void; + setStopping(value: boolean): void; + canCallIntoJs(): boolean; + /** + * Destroy the context and call cleanup hooks. + * Associated {@link Env | Env} will be destroyed. + */ + destroy(): void; +} + +export declare interface ContextOptions { + onExternalMemoryChange?: (current: bigint, old: bigint, delta: bigint) => any; +} + +export declare function createContext(options?: ContextOptions): Context; + +export declare class Deferred implements IStoreValue { + static create(ctx: Context, value: IDeferrdValue): Deferred; + id: number; + ctx: Context; + value: IDeferrdValue; + constructor(ctx: Context, value: IDeferrdValue); + resolve(value: T): void; + reject(reason?: any): void; + dispose(): void; +} + +export declare class EmnapiError extends Error { + constructor(message?: string); +} + +export declare abstract class Env implements IStoreValue { + readonly ctx: Context; + moduleApiVersion: number; + makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void; + makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void; + abort: (msg?: string) => never; + id: number; + openHandleScopes: number; + instanceData: TrackedFinalizer | null; + tryCatch: TryCatch; + refs: number; + reflist: RefTracker; + finalizing_reflist: RefTracker; + pendingFinalizers: RefTracker[]; + lastError: { + errorCode: napi_status; + engineErrorCode: number; + engineReserved: Ptr; + }; + inGcFinalizer: boolean; + constructor(ctx: Context, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never); + /** @virtual */ + canCallIntoJs(): boolean; + terminatedOrTerminating(): boolean; + ref(): void; + unref(): void; + ensureHandle(value: S): Handle; + ensureHandleId(value: any): napi_value; + clearLastError(): napi_status; + setLastError(error_code: napi_status, engine_error_code?: uint32_t, engine_reserved?: void_p): napi_status; + getReturnStatus(): napi_status; + callIntoModule(fn: (env: Env) => T, handleException?: (envObject: Env, value: any) => void): T; + /** @virtual */ + abstract callFinalizer(cb: napi_finalize, data: void_p, hint: void_p): void; + invokeFinalizerFromGC(finalizer: RefTracker): void; + checkGCAccess(): void; + /** @virtual */ + enqueueFinalizer(finalizer: RefTracker): void; + /** @virtual */ + dequeueFinalizer(finalizer: RefTracker): void; + /** @virtual */ + deleteMe(): void; + dispose(): void; + private readonly _bindingMap; + initObjectBinding(value: S): IReferenceBinding; + getObjectBinding(value: S): IReferenceBinding; + setInstanceData(data: number, finalize_cb: number, finalize_hint: number): void; + getInstanceData(): number; +} + +/** @public */ +declare interface External_2 extends Record { +} + +/** @public */ +declare const External_2: { + new (value: number | bigint): External_2; + prototype: null; +}; +export { External_2 as External } + +export declare class Finalizer { + envObject: Env; + private _finalizeCallback; + private _finalizeData; + private _finalizeHint; + private _makeDynCall_vppp; + constructor(envObject: Env, _finalizeCallback?: napi_finalize, _finalizeData?: void_p, _finalizeHint?: void_p); + callback(): napi_finalize; + data(): void_p; + hint(): void_p; + resetEnv(): void; + resetFinalizer(): void; + callFinalizer(): void; + dispose(): void; +} + +export declare function getDefaultContext(): Context; + +/** @public */ +export declare function getExternalValue(external: External_2): number | bigint; + +export declare class Handle { + id: number; + value: S; + constructor(id: number, value: S); + data(): void_p; + isNumber(): boolean; + isBigInt(): boolean; + isString(): boolean; + isFunction(): boolean; + isExternal(): boolean; + isObject(): boolean; + isArray(): boolean; + isArrayBuffer(): boolean; + isTypedArray(): boolean; + isBuffer(BufferConstructor?: BufferCtor): boolean; + isDataView(): boolean; + isDate(): boolean; + isPromise(): boolean; + isBoolean(): boolean; + isUndefined(): boolean; + isSymbol(): boolean; + isNull(): boolean; + dispose(): void; +} + +export declare class HandleScope { + handleStore: HandleStore; + id: number; + parent: HandleScope | null; + child: HandleScope | null; + start: number; + end: number; + private _escapeCalled; + callbackInfo: ICallbackInfo; + constructor(handleStore: HandleStore, id: number, parentScope: HandleScope | null, start: number, end?: number); + add(value: V): Handle; + addExternal(data: void_p): Handle; + dispose(): void; + escape(handle: number): Handle | null; + escapeCalled(): boolean; +} + +export declare class HandleStore { + static UNDEFINED: ConstHandle; + static NULL: ConstHandle; + static FALSE: ConstHandle; + static TRUE: ConstHandle; + static GLOBAL: ConstHandle; + static MIN_ID: 6; + private readonly _values; + private _next; + push(value: S): Handle; + erase(start: number, end: number): void; + get(id: Ptr): Handle | undefined; + swap(a: number, b: number): void; + dispose(): void; +} + +export declare interface ICallbackInfo { + thiz: any; + data: void_p; + args: ArrayLike; + fn: Function; +} + +export declare interface IDeferrdValue { + resolve: (value: T) => void; + reject: (reason?: any) => void; +} + +export declare interface IReferenceBinding { + wrapped: number; + tag: Uint32Array | null; +} + +/** @public */ +export declare function isExternal(object: unknown): object is External_2; + +export declare function isReferenceType(v: any): v is object; + +export declare interface IStoreValue { + id: number; + dispose(): void; + [x: string]: any; +} + +export declare const NAPI_VERSION_EXPERIMENTAL = Version.NAPI_VERSION_EXPERIMENTAL; + +export declare const NODE_API_DEFAULT_MODULE_API_VERSION = Version.NODE_API_DEFAULT_MODULE_API_VERSION; + +export declare const NODE_API_SUPPORTED_VERSION_MAX = Version.NODE_API_SUPPORTED_VERSION_MAX; + +export declare const NODE_API_SUPPORTED_VERSION_MIN = Version.NODE_API_SUPPORTED_VERSION_MIN; + +export declare class NodeEnv extends Env { + filename: string; + private readonly nodeBinding?; + destructing: boolean; + finalizationScheduled: boolean; + constructor(ctx: Context, filename: string, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never, nodeBinding?: any); + deleteMe(): void; + canCallIntoJs(): boolean; + triggerFatalException(err: any): void; + callbackIntoModule(enforceUncaughtExceptionPolicy: boolean, fn: (env: Env) => T): T; + callFinalizer(cb: napi_finalize, data: void_p, hint: void_p): void; + callFinalizerInternal(forceUncaught: int, cb: napi_finalize, data: void_p, hint: void_p): void; + enqueueFinalizer(finalizer: RefTracker): void; + drainFinalizerQueue(): void; +} + +export declare class NotSupportBufferError extends EmnapiError { + constructor(api: string, message: string); +} + +export declare class NotSupportWeakRefError extends EmnapiError { + constructor(api: string, message: string); +} + +export declare class Persistent { + private _ref; + private _param; + private _callback; + private static readonly _registry; + constructor(value: T); + setWeak

(param: P, callback: (param: P) => void): void; + clearWeak(): void; + reset(): void; + isEmpty(): boolean; + deref(): T | undefined; +} + +export declare class Reference extends RefTracker implements IStoreValue { + private static weakCallback; + id: number; + envObject: Env; + private readonly canBeWeak; + private _refcount; + private readonly _ownership; + persistent: Persistent; + static create(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, _unused1?: void_p, _unused2?: void_p, _unused3?: void_p): Reference; + protected constructor(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership); + ref(): number; + unref(): number; + get(envObject?: Env): napi_value; + /** @virtual */ + resetFinalizer(): void; + /** @virtual */ + data(): void_p; + refcount(): number; + ownership(): ReferenceOwnership; + /** @virtual */ + protected callUserFinalizer(): void; + /** @virtual */ + protected invokeFinalizerFromGC(): void; + private _setWeak; + finalize(): void; + dispose(): void; +} + +export declare enum ReferenceOwnership { + kRuntime = 0, + kUserland = 1 +} + +export declare class ReferenceWithData extends Reference { + private readonly _data; + static create(envObject: Env, value: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, data: void_p): ReferenceWithData; + private constructor(); + data(): void_p; +} + +export declare class ReferenceWithFinalizer extends Reference { + private _finalizer; + static create(envObject: Env, value: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): ReferenceWithFinalizer; + private constructor(); + resetFinalizer(): void; + data(): void_p; + protected callUserFinalizer(): void; + protected invokeFinalizerFromGC(): void; + dispose(): void; +} + +export declare class RefTracker { + /** @virtual */ + dispose(): void; + /** @virtual */ + finalize(): void; + private _next; + private _prev; + link(list: RefTracker): void; + unlink(): void; + static finalizeAll(list: RefTracker): void; +} + +export declare class ScopeStore { + private readonly _rootScope; + currentScope: HandleScope; + private readonly _values; + constructor(); + get(id: number): HandleScope | undefined; + openScope(handleStore: HandleStore): HandleScope; + closeScope(): void; + dispose(): void; +} + +export declare class Store { + protected _values: Array; + private _freeList; + private _size; + constructor(); + add(value: V): void; + get(id: Ptr): V | undefined; + has(id: Ptr): boolean; + remove(id: Ptr): void; + dispose(): void; +} + +export declare class TrackedFinalizer extends RefTracker { + private _finalizer; + static create(envObject: Env, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): TrackedFinalizer; + private constructor(); + data(): void_p; + dispose(): void; + finalize(): void; +} + +export declare class TryCatch { + private _exception; + private _caught; + isEmpty(): boolean; + hasCaught(): boolean; + exception(): any; + setError(err: any): void; + reset(): void; + extractException(): any; +} + +export declare const version: string; + +export { } diff --git a/node_modules/@emnapi/runtime/dist/emnapi.min.js b/node_modules/@emnapi/runtime/dist/emnapi.min.js new file mode 100644 index 0000000..afdaf6b --- /dev/null +++ b/node_modules/@emnapi/runtime/dist/emnapi.min.js @@ -0,0 +1 @@ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).emnapi={})}(this,function(t){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},e(t,n)};function n(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}"function"==typeof SuppressedError&&SuppressedError;var i=new WeakMap;function r(t){return i.has(t)}var o=function(){function t(t){Object.setPrototypeOf(this,null),i.set(this,t)}return t.prototype=null,t}();function s(t){if(!r(t))throw new TypeError("not external");return i.get(t)}var a=function(){var t;try{t=new Function}catch(t){return!1}return"function"==typeof t}(),u=function(){if("undefined"!=typeof globalThis)return globalThis;var t=function(){return this}();if(!t&&a)try{t=new Function("return this")()}catch(t){}if(!t){if("undefined"==typeof __webpack_public_path__&&"undefined"!=typeof global)return global;if("undefined"!=typeof window)return window;if("undefined"!=typeof self)return self}return t}(),c=function(){function t(){this._exception=void 0,this._caught=!1}return t.prototype.isEmpty=function(){return!this._caught},t.prototype.hasCaught=function(){return this._caught},t.prototype.exception=function(){return this._exception},t.prototype.setError=function(t){this._caught=!0,this._exception=t},t.prototype.reset=function(){this._caught=!1,this._exception=void 0},t.prototype.extractException=function(){var t=this._exception;return this.reset(),t},t}(),p=function(){var t;try{return Boolean(null===(t=Object.getOwnPropertyDescriptor(Function.prototype,"name"))||void 0===t?void 0:t.configurable)}catch(t){return!1}}(),l="object"==typeof Reflect,f="undefined"!=typeof FinalizationRegistry&&"undefined"!=typeof WeakRef,h=function(){try{var t=Symbol();new WeakRef(t),(new WeakMap).set(t,void 0)}catch(t){return!1}return!0}(),d="undefined"!=typeof BigInt;var y=function(){return"undefined"!=typeof __webpack_public_path__||"undefined"!=typeof __webpack_public_path__?"undefined"!=typeof __non_webpack_require__?__non_webpack_require__:void 0:"undefined"!=typeof require?require:void 0}(),_="function"==typeof MessageChannel?MessageChannel:function(){try{return y("worker_threads").MessageChannel}catch(t){}}(),v="function"==typeof setImmediate?setImmediate.bind(u):function(t){if("function"!=typeof t)throw new TypeError('The "callback" argument must be of type function');if(_){var e=new _;e.port1.onmessage=function(){e.port1.onmessage=null,e=void 0,t()},e.port2.postMessage(null)}else setTimeout(t,0)},g="function"==typeof Buffer?Buffer:function(){try{return y("buffer").Buffer}catch(t){}}(),b="1.11.3",z=2147483647,w=function(){function t(t,e){this.id=t,this.value=e}return t.prototype.data=function(){return s(this.value)},t.prototype.isNumber=function(){return"number"==typeof this.value},t.prototype.isBigInt=function(){return"bigint"==typeof this.value},t.prototype.isString=function(){return"string"==typeof this.value},t.prototype.isFunction=function(){return"function"==typeof this.value},t.prototype.isExternal=function(){return r(this.value)},t.prototype.isObject=function(){return"object"==typeof this.value&&null!==this.value},t.prototype.isArray=function(){return Array.isArray(this.value)},t.prototype.isArrayBuffer=function(){return this.value instanceof ArrayBuffer},t.prototype.isTypedArray=function(){return ArrayBuffer.isView(this.value)&&!(this.value instanceof DataView)},t.prototype.isBuffer=function(t){return!!ArrayBuffer.isView(this.value)||(null!=t||(t=g),"function"==typeof t&&t.isBuffer(this.value))},t.prototype.isDataView=function(){return this.value instanceof DataView},t.prototype.isDate=function(){return this.value instanceof Date},t.prototype.isPromise=function(){return this.value instanceof Promise},t.prototype.isBoolean=function(){return"boolean"==typeof this.value},t.prototype.isUndefined=function(){return void 0===this.value},t.prototype.isSymbol=function(){return"symbol"==typeof this.value},t.prototype.isNull=function(){return null===this.value},t.prototype.dispose=function(){this.value=void 0},t}(),k=function(t){function e(e,n){return t.call(this,e,n)||this}return n(e,t),e.prototype.dispose=function(){},e}(w),m=function(){function t(){this._values=[void 0,t.UNDEFINED,t.NULL,t.FALSE,t.TRUE,t.GLOBAL],this._next=t.MIN_ID}return t.prototype.push=function(t){var e,n=this._next,i=this._values;return n=this.end)return null;this.handleStore.swap(t,this.start);var e=this.handleStore.get(this.start);return this.start++,this.parent.end++,e},t.prototype.escapeCalled=function(){return this._escapeCalled},t}(),S=function(){function t(){this._rootScope=new E(null,0,null,1,m.MIN_ID),this.currentScope=this._rootScope,this._values=[void 0]}return t.prototype.get=function(t){return this._values[t]},t.prototype.openScope=function(t){var e=this.currentScope,n=e.child;if(null!==n)n.start=n.end=e.end;else{var i=e.id+1;n=new E(t,i,e,e.end),this._values[i]=n}return this.currentScope=n,n},t.prototype.closeScope=function(){var t=this.currentScope;this.currentScope=t.parent,t.dispose()},t.prototype.dispose=function(){this.currentScope=this._rootScope,this._values.length=1},t}(),C=function(){function t(){this._next=null,this._prev=null}return t.prototype.dispose=function(){},t.prototype.finalize=function(){},t.prototype.link=function(t){this._prev=t,this._next=t._next,null!==this._next&&(this._next._prev=this),t._next=this},t.prototype.unlink=function(){null!==this._prev&&(this._prev._next=this._next),null!==this._next&&(this._next._prev=this._prev),this._prev=null,this._next=null},t.finalizeAll=function(t){for(;null!==t._next;)t._next.finalize()},t}(),x=function(){function t(t,e,n,i){void 0===e&&(e=0),void 0===n&&(n=0),void 0===i&&(i=0),this.envObject=t,this._finalizeCallback=e,this._finalizeData=n,this._finalizeHint=i,this._makeDynCall_vppp=t.makeDynCall_vppp}return t.prototype.callback=function(){return this._finalizeCallback},t.prototype.data=function(){return this._finalizeData},t.prototype.hint=function(){return this._finalizeHint},t.prototype.resetEnv=function(){this.envObject=void 0},t.prototype.resetFinalizer=function(){this._finalizeCallback=0,this._finalizeData=0,this._finalizeHint=0},t.prototype.callFinalizer=function(){var t=this._finalizeCallback,e=this._finalizeData,n=this._finalizeHint;if(this.resetFinalizer(),t){var i=Number(t);this.envObject?this.envObject.callFinalizer(i,e,n):this._makeDynCall_vppp(i)(0,e,n)}},t.prototype.dispose=function(){this.envObject=void 0,this._makeDynCall_vppp=void 0},t}(),F=function(t){function e(e,n,i,r){var o=t.call(this)||this;return o._finalizer=new x(e,n,i,r),o}return n(e,t),e.create=function(t,n,i,r){var o=new e(t,n,i,r);return o.link(t.finalizing_reflist),o},e.prototype.data=function(){return this._finalizer.data()},e.prototype.dispose=function(){this._finalizer&&(this.unlink(),this._finalizer.envObject.dequeueFinalizer(this),this._finalizer.dispose(),this._finalizer=void 0,t.prototype.dispose.call(this))},e.prototype.finalize=function(){var t;this.unlink();var e=!1;try{this._finalizer.callFinalizer()}catch(n){e=!0,t=n}if(this.dispose(),e)throw t},e}(C);function O(t,e){if(!t.terminatedOrTerminating())throw e}var I=function(){function t(t,e,n,i,r){this.ctx=t,this.moduleApiVersion=e,this.makeDynCall_vppp=n,this.makeDynCall_vp=i,this.abort=r,this.openHandleScopes=0,this.instanceData=null,this.tryCatch=new c,this.refs=1,this.reflist=new C,this.finalizing_reflist=new C,this.pendingFinalizers=[],this.lastError={errorCode:0,engineErrorCode:0,engineReserved:0},this.inGcFinalizer=!1,this._bindingMap=new WeakMap,this.id=0}return t.prototype.canCallIntoJs=function(){return!0},t.prototype.terminatedOrTerminating=function(){return!this.canCallIntoJs()},t.prototype.ref=function(){this.refs++},t.prototype.unref=function(){this.refs--,0===this.refs&&this.dispose()},t.prototype.ensureHandle=function(t){return this.ctx.ensureHandle(t)},t.prototype.ensureHandleId=function(t){return this.ensureHandle(t).id},t.prototype.clearLastError=function(){var t=this.lastError;return 0!==t.errorCode&&(t.errorCode=0),0!==t.engineErrorCode&&(t.engineErrorCode=0),0!==t.engineReserved&&(t.engineReserved=0),0},t.prototype.setLastError=function(t,e,n){void 0===e&&(e=0),void 0===n&&(n=0);var i=this.lastError;return i.errorCode!==t&&(i.errorCode=t),i.engineErrorCode!==e&&(i.engineErrorCode=e),i.engineReserved!==n&&(i.engineReserved=n),t},t.prototype.getReturnStatus=function(){return this.tryCatch.hasCaught()?this.setLastError(10):0},t.prototype.callIntoModule=function(t,e){void 0===e&&(e=O);var n=this.openHandleScopes;this.clearLastError();var i=t(this);(n!==this.openHandleScopes&&this.abort("open_handle_scopes != open_handle_scopes_before"),this.tryCatch.hasCaught())&&e(this,this.tryCatch.extractException());return i},t.prototype.invokeFinalizerFromGC=function(t){if(this.moduleApiVersion!==z)this.enqueueFinalizer(t);else{var e=this.inGcFinalizer;this.inGcFinalizer=!0;try{t.finalize()}finally{this.inGcFinalizer=e}}},t.prototype.checkGCAccess=function(){this.moduleApiVersion===z&&this.inGcFinalizer&&this.abort("Finalizer is calling a function that may affect GC state.\nThe finalizers are run directly from GC and must not affect GC state.\nUse `node_api_post_finalizer` from inside of the finalizer to work around this issue.\nIt schedules the call as a new task in the event loop.")},t.prototype.enqueueFinalizer=function(t){-1===this.pendingFinalizers.indexOf(t)&&this.pendingFinalizers.push(t)},t.prototype.dequeueFinalizer=function(t){var e=this.pendingFinalizers.indexOf(t);-1!==e&&this.pendingFinalizers.splice(e,1)},t.prototype.deleteMe=function(){C.finalizeAll(this.finalizing_reflist),C.finalizeAll(this.reflist),this.tryCatch.extractException(),this.ctx.envStore.remove(this.id)},t.prototype.dispose=function(){0!==this.id&&(this.deleteMe(),this.finalizing_reflist.dispose(),this.reflist.dispose(),this.id=0)},t.prototype.initObjectBinding=function(t){var e={wrapped:0,tag:null};return this._bindingMap.set(t,e),e},t.prototype.getObjectBinding=function(t){return this._bindingMap.has(t)?this._bindingMap.get(t):this.initObjectBinding(t)},t.prototype.setInstanceData=function(t,e,n){this.instanceData&&this.instanceData.dispose(),this.instanceData=F.create(this,e,t,n)},t.prototype.getInstanceData=function(){return this.instanceData?this.instanceData.data():0},t}(),D=function(t){function e(e,n,i,r,o,s,a){var u=t.call(this,e,i,r,o,s)||this;return u.filename=n,u.nodeBinding=a,u.destructing=!1,u.finalizationScheduled=!1,u}return n(e,t),e.prototype.deleteMe=function(){this.destructing=!0,this.drainFinalizerQueue(),t.prototype.deleteMe.call(this)},e.prototype.canCallIntoJs=function(){return t.prototype.canCallIntoJs.call(this)&&this.ctx.canCallIntoJs()},e.prototype.triggerFatalException=function(t){if(this.nodeBinding)this.nodeBinding.napi.fatalException(t);else{if("object"!=typeof process||null===process||"function"!=typeof process._fatalException)throw t;process._fatalException(t)||(console.error(t),process.exit(1))}},e.prototype.callbackIntoModule=function(t,e){return this.callIntoModule(e,function(e,n){if(!e.terminatedOrTerminating()){var i="object"==typeof process&&null!==process,r=!!i&&Boolean(process.execArgv&&-1!==process.execArgv.indexOf("--force-node-api-uncaught-exceptions-policy"));if(e.moduleApiVersion<10&&!r&&!t)(i&&"function"==typeof process.emitWarning?process.emitWarning:function(t,e,n){if(t instanceof Error)console.warn(t.toString());else{var i=n?"[".concat(n,"] "):"";console.warn("".concat(i).concat(e||"Warning",": ").concat(t))}})("Uncaught Node-API callback exception detected, please run node with option --force-node-api-uncaught-exceptions-policy=true to handle those exceptions properly.","DeprecationWarning","DEP0168");else e.triggerFatalException(n)}})},e.prototype.callFinalizer=function(t,e,n){this.callFinalizerInternal(1,t,e,n)},e.prototype.callFinalizerInternal=function(t,e,n,i){var r=this.makeDynCall_vppp(e),o=this.id,s=this.ctx.openScope(this);try{this.callbackIntoModule(Boolean(t),function(){r(o,n,i)})}finally{this.ctx.closeScope(this,s)}},e.prototype.enqueueFinalizer=function(e){var n=this;t.prototype.enqueueFinalizer.call(this,e),this.finalizationScheduled||this.destructing||(this.finalizationScheduled=!0,this.ref(),v(function(){n.finalizationScheduled=!1,n.unref(),n.drainFinalizerQueue()}))},e.prototype.drainFinalizerQueue=function(){for(;this.pendingFinalizers.length>0;){this.pendingFinalizers.shift().finalize()}},e}(I);function R(t,e,n,i,r,o,s){(n="number"!=typeof n?8:n)<8?n=8:n>10&&n!==z&&function(t,e){var n="".concat(t," requires Node-API version ").concat(e,", but this version of Node.js only supports version ").concat(10," add-ons.");throw new Error(n)}(e,n);var a=new D(t,e,n,i,r,o,s);return t.envStore.add(a),t.addCleanupHook(a,function(){a.unref()},0),a}var N=function(t){function e(n){var i=this.constructor,r=t.call(this,n)||this,o=i,s=o.prototype;if(!(r instanceof e)){var a=Object.setPrototypeOf;"function"==typeof a?a.call(Object,r,s):r.__proto__=s,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(r,o)}return r}return n(e,t),e}(Error);Object.defineProperty(N.prototype,"name",{configurable:!0,writable:!0,value:"EmnapiError"});var j=function(t){function e(e,n){return t.call(this,"".concat(e,': The current runtime does not support "FinalizationRegistry" and "WeakRef".').concat(n?" ".concat(n):""))||this}return n(e,t),e}(N);Object.defineProperty(j.prototype,"name",{configurable:!0,writable:!0,value:"NotSupportWeakRefError"});var A=function(t){function e(e,n){return t.call(this,"".concat(e,': The current runtime does not support "Buffer". Consider using buffer polyfill to make sure `globalThis.Buffer` is defined.').concat(n?" ".concat(n):""))||this}return n(e,t),e}(N);Object.defineProperty(A.prototype,"name",{configurable:!0,writable:!0,value:"NotSupportBufferError"});var H,B=function(){function t(t){this._value=t}return t.prototype.deref=function(){return this._value},t.prototype.dispose=function(){this._value=void 0},t}(),M=function(){function t(t){this._ref=new B(t)}return t.prototype.setWeak=function(e,n){if(f&&void 0!==this._ref&&!(this._ref instanceof WeakRef)){var i=this._ref.deref();try{t._registry.register(i,this,this);var r=new WeakRef(i);this._ref.dispose(),this._ref=r,this._param=e,this._callback=n}catch(t){if("symbol"!=typeof i)throw t}}},t.prototype.clearWeak=function(){if(f&&void 0!==this._ref&&this._ref instanceof WeakRef){try{t._registry.unregister(this)}catch(t){}this._param=void 0,this._callback=void 0;var e=this._ref.deref();this._ref=void 0===e?e:new B(e)}},t.prototype.reset=function(){if(f)try{t._registry.unregister(this)}catch(t){}this._param=void 0,this._callback=void 0,this._ref instanceof B&&this._ref.dispose(),this._ref=void 0},t.prototype.isEmpty=function(){return void 0===this._ref},t.prototype.deref=function(){if(void 0!==this._ref)return this._ref.deref()},t._registry=f?new FinalizationRegistry(function(t){t._ref=void 0;var e=t._callback,n=t._param;t._callback=void 0,t._param=void 0,"function"==typeof e&&e(n)}):void 0,t}();t.ReferenceOwnership=void 0,(H=t.ReferenceOwnership||(t.ReferenceOwnership={}))[H.kRuntime=0]="kRuntime",H[H.kUserland=1]="kUserland";var T,W=function(e){function i(t,n,i,r){var o=e.call(this)||this;o.envObject=t,o._refcount=i,o._ownership=r;var s,a=t.ctx.handleStore.get(n);return o.canBeWeak=(s=a).isObject()||s.isFunction()||s.isSymbol(),o.persistent=new M(a.value),o.id=0,0===i&&o._setWeak(),o}return n(i,e),i.weakCallback=function(t){t.persistent.reset(),t.invokeFinalizerFromGC()},i.create=function(t,e,n,r,o,s,a){var u=new i(t,e,n,r);return t.ctx.refStore.add(u),u.link(t.reflist),u},i.prototype.ref=function(){return this.persistent.isEmpty()?0:(1===++this._refcount&&this.canBeWeak&&this.persistent.clearWeak(),this._refcount)},i.prototype.unref=function(){return this.persistent.isEmpty()||0===this._refcount?0:(0===--this._refcount&&this._setWeak(),this._refcount)},i.prototype.get=function(t){if(void 0===t&&(t=this.envObject),this.persistent.isEmpty())return 0;var e=this.persistent.deref();return t.ensureHandle(e).id},i.prototype.resetFinalizer=function(){},i.prototype.data=function(){return 0},i.prototype.refcount=function(){return this._refcount},i.prototype.ownership=function(){return this._ownership},i.prototype.callUserFinalizer=function(){},i.prototype.invokeFinalizerFromGC=function(){this.finalize()},i.prototype._setWeak=function(){this.canBeWeak?this.persistent.setWeak(this,i.weakCallback):this.persistent.reset()},i.prototype.finalize=function(){this.persistent.reset();var e=this._ownership===t.ReferenceOwnership.kRuntime;this.unlink(),this.callUserFinalizer(),e&&this.dispose()},i.prototype.dispose=function(){0!==this.id&&(this.unlink(),this.persistent.reset(),this.envObject.ctx.refStore.remove(this.id),e.prototype.dispose.call(this),this.envObject=void 0,this.id=0)},i}(C),P=function(t){function e(e,n,i,r,o){var s=t.call(this,e,n,i,r)||this;return s._data=o,s}return n(e,t),e.create=function(t,n,i,r,o){var s=new e(t,n,i,r,o);return t.ctx.refStore.add(s),s.link(t.reflist),s},e.prototype.data=function(){return this._data},e}(W),L=function(t){function e(e,n,i,r,o,s,a){var u=t.call(this,e,n,i,r)||this;return u._finalizer=new x(e,o,s,a),u}return n(e,t),e.create=function(t,n,i,r,o,s,a){var u=new e(t,n,i,r,o,s,a);return t.ctx.refStore.add(u),u.link(t.finalizing_reflist),u},e.prototype.resetFinalizer=function(){this._finalizer.resetFinalizer()},e.prototype.data=function(){return this._finalizer.data()},e.prototype.callUserFinalizer=function(){this._finalizer.callFinalizer()},e.prototype.invokeFinalizerFromGC=function(){this._finalizer.envObject.invokeFinalizerFromGC(this)},e.prototype.dispose=function(){this._finalizer&&(this._finalizer.envObject.dequeueFinalizer(this),this._finalizer.dispose(),t.prototype.dispose.call(this),this._finalizer=void 0)},e}(W),U=function(){function t(t,e){Object.defineProperties(this,{id:{configurable:!0,enumerable:!0,value:0,writable:!0},ctx:{configurable:!0,enumerable:!0,value:t,writable:!0},value:{configurable:!0,enumerable:!0,value:e,writable:!0}})}return t.create=function(e,n){var i=new t(e,n);return e.deferredStore.add(i),i},t.prototype.resolve=function(t){this.value.resolve(t),this.dispose()},t.prototype.reject=function(t){this.value.reject(t),this.dispose()},t.prototype.dispose=function(){this.ctx.deferredStore.remove(this.id),this.id=0,this.value=null,this.ctx=null},t}(),V=function(){function t(){this._values=[void 0],this._values.length=4,this._size=1,this._freeList=[]}return t.prototype.add=function(t){var e;if(this._freeList.length)e=this._freeList.shift();else{e=this._size,this._size++;var n=this._values.length;e>=n&&(this._values.length=n+(n>>1)+16)}t.id=e,this._values[e]=t},t.prototype.get=function(t){return this._values[t]},t.prototype.has=function(t){return void 0!==this._values[t]},t.prototype.remove=function(t){var e=this._values[t];e&&(e.id=0,this._values[t]=void 0,this._freeList.push(Number(t)))},t.prototype.dispose=function(){for(var t=1;t0)throw new Error("Can not add same fn and arg twice");this._cleanupHooks.push(new Q(t,e,n,this._cleanupHookCounter++))},t.prototype.remove=function(t,e,n){for(var i=0;i{function t(t){Object.setPrototypeOf(this,null),e.set(this,t)}return t.prototype=null,t})();function n(i){if(!t(i))throw new TypeError("not external");return e.get(i)}const s=function(){let e;try{e=new Function}catch(e){return!1}return"function"==typeof e}(),r=function(){if("undefined"!=typeof globalThis)return globalThis;let e=function(){return this}();if(!e&&s)try{e=new Function("return this")()}catch(e){}if(!e){if("undefined"==typeof __webpack_public_path__&&"undefined"!=typeof global)return global;if("undefined"!=typeof window)return window;if("undefined"!=typeof self)return self}return e}();class a{constructor(){this._exception=void 0,this._caught=!1}isEmpty(){return!this._caught}hasCaught(){return this._caught}exception(){return this._exception}setError(e){this._caught=!0,this._exception=e}reset(){this._caught=!1,this._exception=void 0}extractException(){const e=this._exception;return this.reset(),e}}const o=function(){var e;try{return Boolean(null===(e=Object.getOwnPropertyDescriptor(Function.prototype,"name"))||void 0===e?void 0:e.configurable)}catch(e){return!1}}(),l="object"==typeof Reflect,c="undefined"!=typeof FinalizationRegistry&&"undefined"!=typeof WeakRef,u=function(){try{const e=Symbol();new WeakRef(e),(new WeakMap).set(e,void 0)}catch(e){return!1}return!0}(),h="undefined"!=typeof BigInt;function p(e){return"object"==typeof e&&null!==e||"function"==typeof e}const f=function(){let e;return e="undefined"!=typeof __webpack_public_path__||"undefined"!=typeof __webpack_public_path__?"undefined"!=typeof __non_webpack_require__?__non_webpack_require__:void 0:"undefined"!=typeof require?require:void 0,e}(),d="function"==typeof MessageChannel?MessageChannel:function(){try{return f("worker_threads").MessageChannel}catch(e){}}(),_="function"==typeof setImmediate?setImmediate.bind(r):function(e){if("function"!=typeof e)throw new TypeError('The "callback" argument must be of type function');if(d){let t=new d;t.port1.onmessage=function(){t.port1.onmessage=null,t=void 0,e()},t.port2.postMessage(null)}else setTimeout(e,0)},v="function"==typeof Buffer?Buffer:function(){try{return f("buffer").Buffer}catch(e){}}(),g="1.11.3",y=1,b=10,z=2147483647,k=8;class w{constructor(e,t){this.id=e,this.value=t}data(){return n(this.value)}isNumber(){return"number"==typeof this.value}isBigInt(){return"bigint"==typeof this.value}isString(){return"string"==typeof this.value}isFunction(){return"function"==typeof this.value}isExternal(){return t(this.value)}isObject(){return"object"==typeof this.value&&null!==this.value}isArray(){return Array.isArray(this.value)}isArrayBuffer(){return this.value instanceof ArrayBuffer}isTypedArray(){return ArrayBuffer.isView(this.value)&&!(this.value instanceof DataView)}isBuffer(e){return!!ArrayBuffer.isView(this.value)||(null!=e||(e=v),"function"==typeof e&&e.isBuffer(this.value))}isDataView(){return this.value instanceof DataView}isDate(){return this.value instanceof Date}isPromise(){return this.value instanceof Promise}isBoolean(){return"boolean"==typeof this.value}isUndefined(){return void 0===this.value}isSymbol(){return"symbol"==typeof this.value}isNull(){return null===this.value}dispose(){this.value=void 0}}class m extends w{constructor(e,t){super(e,t)}dispose(){}}class C{constructor(){this._values=[void 0,C.UNDEFINED,C.NULL,C.FALSE,C.TRUE,C.GLOBAL],this._next=C.MIN_ID}push(e){let t;const i=this._next,n=this._values;return i=this.end)return null;this.handleStore.swap(e,this.start);const t=this.handleStore.get(this.start);return this.start++,this.parent.end++,t}escapeCalled(){return this._escapeCalled}}class x{constructor(){this._rootScope=new S(null,0,null,1,C.MIN_ID),this.currentScope=this._rootScope,this._values=[void 0]}get(e){return this._values[e]}openScope(e){const t=this.currentScope;let i=t.child;if(null!==i)i.start=i.end=t.end;else{const n=t.id+1;i=new S(e,n,t,t.end),this._values[n]=i}return this.currentScope=i,i}closeScope(){const e=this.currentScope;this.currentScope=e.parent,e.dispose()}dispose(){this.currentScope=this._rootScope,this._values.length=1}}class E{constructor(){this._next=null,this._prev=null}dispose(){}finalize(){}link(e){this._prev=e,this._next=e._next,null!==this._next&&(this._next._prev=this),e._next=this}unlink(){null!==this._prev&&(this._prev._next=this._next),null!==this._next&&(this._next._prev=this._prev),this._prev=null,this._next=null}static finalizeAll(e){for(;null!==e._next;)e._next.finalize()}}class F{constructor(e,t=0,i=0,n=0){this.envObject=e,this._finalizeCallback=t,this._finalizeData=i,this._finalizeHint=n,this._makeDynCall_vppp=e.makeDynCall_vppp}callback(){return this._finalizeCallback}data(){return this._finalizeData}hint(){return this._finalizeHint}resetEnv(){this.envObject=void 0}resetFinalizer(){this._finalizeCallback=0,this._finalizeData=0,this._finalizeHint=0}callFinalizer(){const e=this._finalizeCallback,t=this._finalizeData,i=this._finalizeHint;if(this.resetFinalizer(),!e)return;const n=Number(e);this.envObject?this.envObject.callFinalizer(n,t,i):this._makeDynCall_vppp(n)(0,t,i)}dispose(){this.envObject=void 0,this._makeDynCall_vppp=void 0}}class I extends E{static create(e,t,i,n){const s=new I(e,t,i,n);return s.link(e.finalizing_reflist),s}constructor(e,t,i,n){super(),this._finalizer=new F(e,t,i,n)}data(){return this._finalizer.data()}dispose(){this._finalizer&&(this.unlink(),this._finalizer.envObject.dequeueFinalizer(this),this._finalizer.dispose(),this._finalizer=void 0,super.dispose())}finalize(){let e;this.unlink();let t=!1;try{this._finalizer.callFinalizer()}catch(i){t=!0,e=i}if(this.dispose(),t)throw e}}function D(e,t){if(!e.terminatedOrTerminating())throw t}class O{constructor(e,t,i,n,s){this.ctx=e,this.moduleApiVersion=t,this.makeDynCall_vppp=i,this.makeDynCall_vp=n,this.abort=s,this.openHandleScopes=0,this.instanceData=null,this.tryCatch=new a,this.refs=1,this.reflist=new E,this.finalizing_reflist=new E,this.pendingFinalizers=[],this.lastError={errorCode:0,engineErrorCode:0,engineReserved:0},this.inGcFinalizer=!1,this._bindingMap=new WeakMap,this.id=0}canCallIntoJs(){return!0}terminatedOrTerminating(){return!this.canCallIntoJs()}ref(){this.refs++}unref(){this.refs--,0===this.refs&&this.dispose()}ensureHandle(e){return this.ctx.ensureHandle(e)}ensureHandleId(e){return this.ensureHandle(e).id}clearLastError(){const e=this.lastError;return 0!==e.errorCode&&(e.errorCode=0),0!==e.engineErrorCode&&(e.engineErrorCode=0),0!==e.engineReserved&&(e.engineReserved=0),0}setLastError(e,t=0,i=0){const n=this.lastError;return n.errorCode!==e&&(n.errorCode=e),n.engineErrorCode!==t&&(n.engineErrorCode=t),n.engineReserved!==i&&(n.engineReserved=i),e}getReturnStatus(){return this.tryCatch.hasCaught()?this.setLastError(10):0}callIntoModule(e,t=D){const i=this.openHandleScopes;this.clearLastError();const n=e(this);if(i!==this.openHandleScopes&&this.abort("open_handle_scopes != open_handle_scopes_before"),this.tryCatch.hasCaught()){t(this,this.tryCatch.extractException())}return n}invokeFinalizerFromGC(e){if(this.moduleApiVersion!==z)this.enqueueFinalizer(e);else{const t=this.inGcFinalizer;this.inGcFinalizer=!0;try{e.finalize()}finally{this.inGcFinalizer=t}}}checkGCAccess(){this.moduleApiVersion===z&&this.inGcFinalizer&&this.abort("Finalizer is calling a function that may affect GC state.\nThe finalizers are run directly from GC and must not affect GC state.\nUse `node_api_post_finalizer` from inside of the finalizer to work around this issue.\nIt schedules the call as a new task in the event loop.")}enqueueFinalizer(e){-1===this.pendingFinalizers.indexOf(e)&&this.pendingFinalizers.push(e)}dequeueFinalizer(e){const t=this.pendingFinalizers.indexOf(e);-1!==t&&this.pendingFinalizers.splice(t,1)}deleteMe(){E.finalizeAll(this.finalizing_reflist),E.finalizeAll(this.reflist),this.tryCatch.extractException(),this.ctx.envStore.remove(this.id)}dispose(){0!==this.id&&(this.deleteMe(),this.finalizing_reflist.dispose(),this.reflist.dispose(),this.id=0)}initObjectBinding(e){const t={wrapped:0,tag:null};return this._bindingMap.set(e,t),t}getObjectBinding(e){return this._bindingMap.has(e)?this._bindingMap.get(e):this.initObjectBinding(e)}setInstanceData(e,t,i){this.instanceData&&this.instanceData.dispose(),this.instanceData=I.create(this,t,e,i)}getInstanceData(){return this.instanceData?this.instanceData.data():0}}class j extends O{constructor(e,t,i,n,s,r,a){super(e,i,n,s,r),this.filename=t,this.nodeBinding=a,this.destructing=!1,this.finalizationScheduled=!1}deleteMe(){this.destructing=!0,this.drainFinalizerQueue(),super.deleteMe()}canCallIntoJs(){return super.canCallIntoJs()&&this.ctx.canCallIntoJs()}triggerFatalException(e){if(this.nodeBinding)this.nodeBinding.napi.fatalException(e);else{if("object"!=typeof process||null===process||"function"!=typeof process._fatalException)throw e;process._fatalException(e)||(console.error(e),process.exit(1))}}callbackIntoModule(e,t){return this.callIntoModule(t,(t,i)=>{if(t.terminatedOrTerminating())return;const n="object"==typeof process&&null!==process,s=!!n&&Boolean(process.execArgv&&-1!==process.execArgv.indexOf("--force-node-api-uncaught-exceptions-policy"));if(t.moduleApiVersion<10&&!s&&!e){return void(n&&"function"==typeof process.emitWarning?process.emitWarning:function(e,t,i){if(e instanceof Error)console.warn(e.toString());else{const n=i?`[${i}] `:"";console.warn(`${n}${t||"Warning"}: ${e}`)}})("Uncaught Node-API callback exception detected, please run node with option --force-node-api-uncaught-exceptions-policy=true to handle those exceptions properly.","DeprecationWarning","DEP0168")}t.triggerFatalException(i)})}callFinalizer(e,t,i){this.callFinalizerInternal(1,e,t,i)}callFinalizerInternal(e,t,i,n){const s=this.makeDynCall_vppp(t),r=this.id,a=this.ctx.openScope(this);try{this.callbackIntoModule(Boolean(e),()=>{s(r,i,n)})}finally{this.ctx.closeScope(this,a)}}enqueueFinalizer(e){super.enqueueFinalizer(e),this.finalizationScheduled||this.destructing||(this.finalizationScheduled=!0,this.ref(),_(()=>{this.finalizationScheduled=!1,this.unref(),this.drainFinalizerQueue()}))}drainFinalizerQueue(){for(;this.pendingFinalizers.length>0;){this.pendingFinalizers.shift().finalize()}}}function B(e,t,i,n,s,r,a){(i="number"!=typeof i?8:i)<8?i=8:i>10&&i!==z&&function(e,t){throw new Error(`${e} requires Node-API version ${t}, but this version of Node.js only supports version 10 add-ons.`)}(t,i);const o=new j(e,t,i,n,s,r,a);return e.envStore.add(o),e.addCleanupHook(o,()=>{o.unref()},0),o}class H extends Error{constructor(e){super(e);const t=new.target,i=t.prototype;if(!(this instanceof H)){const e=Object.setPrototypeOf;"function"==typeof e?e.call(Object,this,i):this.__proto__=i,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,t)}}}Object.defineProperty(H.prototype,"name",{configurable:!0,writable:!0,value:"EmnapiError"});class R extends H{constructor(e,t){super(`${e}: The current runtime does not support "FinalizationRegistry" and "WeakRef".${t?` ${t}`:""}`)}}Object.defineProperty(R.prototype,"name",{configurable:!0,writable:!0,value:"NotSupportWeakRefError"});class N extends H{constructor(e,t){super(`${e}: The current runtime does not support "Buffer". Consider using buffer polyfill to make sure \`globalThis.Buffer\` is defined.${t?` ${t}`:""}`)}}Object.defineProperty(N.prototype,"name",{configurable:!0,writable:!0,value:"NotSupportBufferError"});class A{constructor(e){this._value=e}deref(){return this._value}dispose(){this._value=void 0}}class M{constructor(e){this._ref=new A(e)}setWeak(e,t){if(!c||void 0===this._ref||this._ref instanceof WeakRef)return;const i=this._ref.deref();try{M._registry.register(i,this,this);const n=new WeakRef(i);this._ref.dispose(),this._ref=n,this._param=e,this._callback=t}catch(e){if("symbol"!=typeof i)throw e}}clearWeak(){if(c&&void 0!==this._ref&&this._ref instanceof WeakRef){try{M._registry.unregister(this)}catch(e){}this._param=void 0,this._callback=void 0;const e=this._ref.deref();this._ref=void 0===e?e:new A(e)}}reset(){if(c)try{M._registry.unregister(this)}catch(e){}this._param=void 0,this._callback=void 0,this._ref instanceof A&&this._ref.dispose(),this._ref=void 0}isEmpty(){return void 0===this._ref}deref(){if(void 0!==this._ref)return this._ref.deref()}}var W;M._registry=c?new FinalizationRegistry(e=>{e._ref=void 0;const t=e._callback,i=e._param;e._callback=void 0,e._param=void 0,"function"==typeof t&&t(i)}):void 0,function(e){e[e.kRuntime=0]="kRuntime",e[e.kUserland=1]="kUserland"}(W||(W={}));class L extends E{static weakCallback(e){e.persistent.reset(),e.invokeFinalizerFromGC()}static create(e,t,i,n,s,r,a){const o=new L(e,t,i,n);return e.ctx.refStore.add(o),o.link(e.reflist),o}constructor(e,t,i,n){super(),this.envObject=e,this._refcount=i,this._ownership=n;const s=e.ctx.handleStore.get(t);var r;this.canBeWeak=(r=s).isObject()||r.isFunction()||r.isSymbol(),this.persistent=new M(s.value),this.id=0,0===i&&this._setWeak()}ref(){return this.persistent.isEmpty()?0:(1===++this._refcount&&this.canBeWeak&&this.persistent.clearWeak(),this._refcount)}unref(){return this.persistent.isEmpty()||0===this._refcount?0:(0===--this._refcount&&this._setWeak(),this._refcount)}get(e=this.envObject){if(this.persistent.isEmpty())return 0;const t=this.persistent.deref();return e.ensureHandle(t).id}resetFinalizer(){}data(){return 0}refcount(){return this._refcount}ownership(){return this._ownership}callUserFinalizer(){}invokeFinalizerFromGC(){this.finalize()}_setWeak(){this.canBeWeak?this.persistent.setWeak(this,L.weakCallback):this.persistent.reset()}finalize(){this.persistent.reset();const e=this._ownership===W.kRuntime;this.unlink(),this.callUserFinalizer(),e&&this.dispose()}dispose(){0!==this.id&&(this.unlink(),this.persistent.reset(),this.envObject.ctx.refStore.remove(this.id),super.dispose(),this.envObject=void 0,this.id=0)}}class T extends L{static create(e,t,i,n,s){const r=new T(e,t,i,n,s);return e.ctx.refStore.add(r),r.link(e.reflist),r}constructor(e,t,i,n,s){super(e,t,i,n),this._data=s}data(){return this._data}}class U extends L{static create(e,t,i,n,s,r,a){const o=new U(e,t,i,n,s,r,a);return e.ctx.refStore.add(o),o.link(e.finalizing_reflist),o}constructor(e,t,i,n,s,r,a){super(e,t,i,n),this._finalizer=new F(e,s,r,a)}resetFinalizer(){this._finalizer.resetFinalizer()}data(){return this._finalizer.data()}callUserFinalizer(){this._finalizer.callFinalizer()}invokeFinalizerFromGC(){this._finalizer.envObject.invokeFinalizerFromGC(this)}dispose(){this._finalizer&&(this._finalizer.envObject.dequeueFinalizer(this),this._finalizer.dispose(),super.dispose(),this._finalizer=void 0)}}class P{static create(e,t){const i=new P(e,t);return e.deferredStore.add(i),i}constructor(e,t){Object.defineProperties(this,{id:{configurable:!0,enumerable:!0,value:0,writable:!0},ctx:{configurable:!0,enumerable:!0,value:e,writable:!0},value:{configurable:!0,enumerable:!0,value:t,writable:!0}})}resolve(e){this.value.resolve(e),this.dispose()}reject(e){this.value.reject(e),this.dispose()}dispose(){this.ctx.deferredStore.remove(this.id),this.id=0,this.value=null,this.ctx=null}}class G{constructor(){this._values=[void 0],this._values.length=4,this._size=1,this._freeList=[]}add(e){let t;if(this._freeList.length)t=this._freeList.shift();else{t=this._size,this._size++;const e=this._values.length;t>=e&&(this._values.length=e+(e>>1)+16)}e.id=t,this._values[t]=e}get(e){return this._values[e]}has(e){return void 0!==this._values[e]}remove(e){const t=this._values[e];t&&(t.id=0,this._values[e]=void 0,this._freeList.push(Number(e)))}dispose(){for(let e=1;en.envObject===e&&n.fn===t&&n.arg===i).length>0)throw new Error("Can not add same fn and arg twice");this._cleanupHooks.push(new J(e,t,i,this._cleanupHookCounter++))}remove(e,t,i){for(let n=0;nt.order-e.order);for(let t=0;t{this._suppressDestroy||this.destroy()}))}suppressDestroy(){this._suppressDestroy=!0}getRuntimeVersions(){return{version:g,NODE_API_SUPPORTED_VERSION_MAX:10,NAPI_VERSION_EXPERIMENTAL:z,NODE_API_DEFAULT_MODULE_API_VERSION:8}}createNotSupportWeakRefError(e,t){return new R(e,t)}createNotSupportBufferError(e,t){return new N(e,t)}createReference(e,t,i,n){return L.create(e,t,i,n)}createReferenceWithData(e,t,i,n,s){return T.create(e,t,i,n,s)}createReferenceWithFinalizer(e,t,i,n,s=0,r=0,a=0){return U.create(e,t,i,n,s,r,a)}createDeferred(e){return P.create(this,e)}adjustAmountOfExternalAllocatedMemory(e){return this._externalMemory.adjust(e)}createEnv(e,t,i,n,s,r){return B(this,e,t,i,n,s,r)}createTrackedFinalizer(e,t,i,n){return I.create(e,t,i,n)}getCurrentScope(){return this.scopeStore.currentScope}addToCurrentScope(e){return this.scopeStore.currentScope.add(e)}openScope(e){const t=this.scopeStore.openScope(this.handleStore);return e&&e.openHandleScopes++,t}closeScope(e,t){e&&0===e.openHandleScopes||(this.scopeStore.closeScope(),e&&e.openHandleScopes--)}ensureHandle(e){switch(e){case void 0:return C.UNDEFINED;case null:return C.NULL;case!0:return C.TRUE;case!1:return C.FALSE;case r:return C.GLOBAL}return this.addToCurrentScope(e)}addCleanupHook(e,t,i){this.cleanupQueue.add(e,t,i)}removeCleanupHook(e,t,i){this.cleanupQueue.remove(e,t,i)}runCleanup(){for(;!this.cleanupQueue.empty();)this.cleanupQueue.drain()}increaseWaitingRequestCounter(){var e;null===(e=this.refCounter)||void 0===e||e.increase()}decreaseWaitingRequestCounter(){var e;null===(e=this.refCounter)||void 0===e||e.decrease()}setCanCallIntoJs(e){this._canCallIntoJs=e}setStopping(e){this._isStopping=e}canCallIntoJs(){return this._canCallIntoJs&&!this._isStopping}destroy(){this.setStopping(!0),this.setCanCallIntoJs(!1),this.runCleanup()}}let Y;function Z(e){return new K(e)}function ee(){return Y||(Y=Z()),Y}export{m as ConstHandle,K as Context,P as Deferred,H as EmnapiError,O as Env,i as External,F as Finalizer,w as Handle,S as HandleScope,C as HandleStore,z as NAPI_VERSION_EXPERIMENTAL,k as NODE_API_DEFAULT_MODULE_API_VERSION,b as NODE_API_SUPPORTED_VERSION_MAX,y as NODE_API_SUPPORTED_VERSION_MIN,j as NodeEnv,N as NotSupportBufferError,R as NotSupportWeakRefError,M as Persistent,E as RefTracker,L as Reference,W as ReferenceOwnership,T as ReferenceWithData,U as ReferenceWithFinalizer,x as ScopeStore,G as Store,I as TrackedFinalizer,a as TryCatch,Z as createContext,ee as getDefaultContext,n as getExternalValue,t as isExternal,p as isReferenceType,g as version}; diff --git a/node_modules/@emnapi/runtime/dist/emnapi.mjs b/node_modules/@emnapi/runtime/dist/emnapi.mjs new file mode 100644 index 0000000..18e8115 --- /dev/null +++ b/node_modules/@emnapi/runtime/dist/emnapi.mjs @@ -0,0 +1,1367 @@ +const externalValue = new WeakMap(); +function isExternal(object) { + return externalValue.has(object); +} +const External = (() => { + function External(value) { + Object.setPrototypeOf(this, null); + externalValue.set(this, value); + } + External.prototype = null; + return External; +})(); +function getExternalValue(external) { + if (!isExternal(external)) { + throw new TypeError('not external'); + } + return externalValue.get(external); +} + +const supportNewFunction = (function () { + let f; + try { + f = new Function(); + } + catch (_) { + return false; + } + return typeof f === 'function'; +})(); +const _global = (function () { + if (typeof globalThis !== 'undefined') + return globalThis; + let g = (function () { return this; })(); + if (!g && supportNewFunction) { + try { + g = new Function('return this')(); + } + catch (_) { } + } + if (!g) { + if (typeof __webpack_public_path__ === 'undefined') { + if (typeof global !== 'undefined') + return global; + } + if (typeof window !== 'undefined') + return window; + if (typeof self !== 'undefined') + return self; + } + return g; +})(); +class TryCatch { + constructor() { + this._exception = undefined; + this._caught = false; + } + isEmpty() { + return !this._caught; + } + hasCaught() { + return this._caught; + } + exception() { + return this._exception; + } + setError(err) { + this._caught = true; + this._exception = err; + } + reset() { + this._caught = false; + this._exception = undefined; + } + extractException() { + const e = this._exception; + this.reset(); + return e; + } +} +const canSetFunctionName = (function () { + var _a; + try { + return Boolean((_a = Object.getOwnPropertyDescriptor(Function.prototype, 'name')) === null || _a === void 0 ? void 0 : _a.configurable); + } + catch (_) { + return false; + } +})(); +const supportReflect = typeof Reflect === 'object'; +const supportFinalizer = (typeof FinalizationRegistry !== 'undefined') && (typeof WeakRef !== 'undefined'); +const supportWeakSymbol = (function () { + try { + const sym = Symbol(); + new WeakRef(sym); + new WeakMap().set(sym, undefined); + } + catch (_) { + return false; + } + return true; +})(); +const supportBigInt = typeof BigInt !== 'undefined'; +function isReferenceType(v) { + return (typeof v === 'object' && v !== null) || typeof v === 'function'; +} +const _require = (function () { + let nativeRequire; + if (typeof __webpack_public_path__ !== 'undefined') { + nativeRequire = (function () { + return typeof __non_webpack_require__ !== 'undefined' ? __non_webpack_require__ : undefined; + })(); + } + else { + nativeRequire = (function () { + return typeof __webpack_public_path__ !== 'undefined' ? (typeof __non_webpack_require__ !== 'undefined' ? __non_webpack_require__ : undefined) : (typeof require !== 'undefined' ? require : undefined); + })(); + } + return nativeRequire; +})(); +const _MessageChannel = typeof MessageChannel === 'function' + ? MessageChannel + : (function () { + try { + return _require('worker_threads').MessageChannel; + } + catch (_) { } + return undefined; + })(); +const _setImmediate = typeof setImmediate === 'function' + ? setImmediate.bind(_global) + : function (callback) { + if (typeof callback !== 'function') { + throw new TypeError('The "callback" argument must be of type function'); + } + if (_MessageChannel) { + let channel = new _MessageChannel(); + channel.port1.onmessage = function () { + channel.port1.onmessage = null; + channel = undefined; + callback(); + }; + channel.port2.postMessage(null); + } + else { + setTimeout(callback, 0); + } + }; +const _Buffer = typeof Buffer === 'function' + ? Buffer + : (function () { + try { + return _require('buffer').Buffer; + } + catch (_) { } + return undefined; + })(); +const version = "1.11.3"; +const NODE_API_SUPPORTED_VERSION_MIN = 1; +const NODE_API_SUPPORTED_VERSION_MAX = 10; +const NAPI_VERSION_EXPERIMENTAL = 2147483647; +const NODE_API_DEFAULT_MODULE_API_VERSION = 8; + +class Handle { + constructor(id, value) { + this.id = id; + this.value = value; + } + data() { + return getExternalValue(this.value); + } + isNumber() { + return typeof this.value === 'number'; + } + isBigInt() { + return typeof this.value === 'bigint'; + } + isString() { + return typeof this.value === 'string'; + } + isFunction() { + return typeof this.value === 'function'; + } + isExternal() { + return isExternal(this.value); + } + isObject() { + return typeof this.value === 'object' && this.value !== null; + } + isArray() { + return Array.isArray(this.value); + } + isArrayBuffer() { + return (this.value instanceof ArrayBuffer); + } + isTypedArray() { + return (ArrayBuffer.isView(this.value)) && !(this.value instanceof DataView); + } + isBuffer(BufferConstructor) { + if (ArrayBuffer.isView(this.value)) + return true; + BufferConstructor !== null && BufferConstructor !== void 0 ? BufferConstructor : (BufferConstructor = _Buffer); + return typeof BufferConstructor === 'function' && BufferConstructor.isBuffer(this.value); + } + isDataView() { + return (this.value instanceof DataView); + } + isDate() { + return (this.value instanceof Date); + } + isPromise() { + return (this.value instanceof Promise); + } + isBoolean() { + return typeof this.value === 'boolean'; + } + isUndefined() { + return this.value === undefined; + } + isSymbol() { + return typeof this.value === 'symbol'; + } + isNull() { + return this.value === null; + } + dispose() { + this.value = undefined; + } +} +class ConstHandle extends Handle { + constructor(id, value) { + super(id, value); + } + dispose() { } +} +class HandleStore { + constructor() { + this._values = [ + undefined, + HandleStore.UNDEFINED, + HandleStore.NULL, + HandleStore.FALSE, + HandleStore.TRUE, + HandleStore.GLOBAL + ]; + this._next = HandleStore.MIN_ID; + } + push(value) { + let h; + const next = this._next; + const values = this._values; + if (next < values.length) { + h = values[next]; + h.value = value; + } + else { + h = new Handle(next, value); + values[next] = h; + } + this._next++; + return h; + } + erase(start, end) { + this._next = start; + const values = this._values; + for (let i = start; i < end; ++i) { + values[i].dispose(); + } + } + get(id) { + return this._values[id]; + } + swap(a, b) { + const values = this._values; + const h = values[a]; + values[a] = values[b]; + values[a].id = Number(a); + values[b] = h; + h.id = Number(b); + } + dispose() { + this._values.length = HandleStore.MIN_ID; + this._next = HandleStore.MIN_ID; + } +} +HandleStore.UNDEFINED = new ConstHandle(1, undefined); +HandleStore.NULL = new ConstHandle(2, null); +HandleStore.FALSE = new ConstHandle(3, false); +HandleStore.TRUE = new ConstHandle(4, true); +HandleStore.GLOBAL = new ConstHandle(5, _global); +HandleStore.MIN_ID = 6; + +class HandleScope { + constructor(handleStore, id, parentScope, start, end = start) { + this.handleStore = handleStore; + this.id = id; + this.parent = parentScope; + this.child = null; + if (parentScope !== null) + parentScope.child = this; + this.start = start; + this.end = end; + this._escapeCalled = false; + this.callbackInfo = { + thiz: undefined, + data: 0, + args: undefined, + fn: undefined + }; + } + add(value) { + const h = this.handleStore.push(value); + this.end++; + return h; + } + addExternal(data) { + return this.add(new External(data)); + } + dispose() { + if (this._escapeCalled) + this._escapeCalled = false; + if (this.start === this.end) + return; + this.handleStore.erase(this.start, this.end); + } + escape(handle) { + if (this._escapeCalled) + return null; + this._escapeCalled = true; + if (handle < this.start || handle >= this.end) { + return null; + } + this.handleStore.swap(handle, this.start); + const h = this.handleStore.get(this.start); + this.start++; + this.parent.end++; + return h; + } + escapeCalled() { + return this._escapeCalled; + } +} + +class ScopeStore { + constructor() { + this._rootScope = new HandleScope(null, 0, null, 1, HandleStore.MIN_ID); + this.currentScope = this._rootScope; + this._values = [undefined]; + } + get(id) { + return this._values[id]; + } + openScope(handleStore) { + const currentScope = this.currentScope; + let scope = currentScope.child; + if (scope !== null) { + scope.start = scope.end = currentScope.end; + } + else { + const id = currentScope.id + 1; + scope = new HandleScope(handleStore, id, currentScope, currentScope.end); + this._values[id] = scope; + } + this.currentScope = scope; + return scope; + } + closeScope() { + const scope = this.currentScope; + this.currentScope = scope.parent; + scope.dispose(); + } + dispose() { + this.currentScope = this._rootScope; + this._values.length = 1; + } +} + +class RefTracker { + constructor() { + this._next = null; + this._prev = null; + } + dispose() { } + finalize() { } + link(list) { + this._prev = list; + this._next = list._next; + if (this._next !== null) { + this._next._prev = this; + } + list._next = this; + } + unlink() { + if (this._prev !== null) { + this._prev._next = this._next; + } + if (this._next !== null) { + this._next._prev = this._prev; + } + this._prev = null; + this._next = null; + } + static finalizeAll(list) { + while (list._next !== null) { + list._next.finalize(); + } + } +} + +class Finalizer { + constructor(envObject, _finalizeCallback = 0, _finalizeData = 0, _finalizeHint = 0) { + this.envObject = envObject; + this._finalizeCallback = _finalizeCallback; + this._finalizeData = _finalizeData; + this._finalizeHint = _finalizeHint; + this._makeDynCall_vppp = envObject.makeDynCall_vppp; + } + callback() { return this._finalizeCallback; } + data() { return this._finalizeData; } + hint() { return this._finalizeHint; } + resetEnv() { + this.envObject = undefined; + } + resetFinalizer() { + this._finalizeCallback = 0; + this._finalizeData = 0; + this._finalizeHint = 0; + } + callFinalizer() { + const finalize_callback = this._finalizeCallback; + const finalize_data = this._finalizeData; + const finalize_hint = this._finalizeHint; + this.resetFinalizer(); + if (!finalize_callback) + return; + const fini = Number(finalize_callback); + if (!this.envObject) { + this._makeDynCall_vppp(fini)(0, finalize_data, finalize_hint); + } + else { + this.envObject.callFinalizer(fini, finalize_data, finalize_hint); + } + } + dispose() { + this.envObject = undefined; + this._makeDynCall_vppp = undefined; + } +} + +class TrackedFinalizer extends RefTracker { + static create(envObject, finalize_callback, finalize_data, finalize_hint) { + const finalizer = new TrackedFinalizer(envObject, finalize_callback, finalize_data, finalize_hint); + finalizer.link(envObject.finalizing_reflist); + return finalizer; + } + constructor(envObject, finalize_callback, finalize_data, finalize_hint) { + super(); + this._finalizer = new Finalizer(envObject, finalize_callback, finalize_data, finalize_hint); + } + data() { + return this._finalizer.data(); + } + dispose() { + if (!this._finalizer) + return; + this.unlink(); + this._finalizer.envObject.dequeueFinalizer(this); + this._finalizer.dispose(); + this._finalizer = undefined; + super.dispose(); + } + finalize() { + this.unlink(); + let error; + let caught = false; + try { + this._finalizer.callFinalizer(); + } + catch (err) { + caught = true; + error = err; + } + this.dispose(); + if (caught) { + throw error; + } + } +} + +function throwNodeApiVersionError(moduleName, moduleApiVersion) { + const errorMessage = `${moduleName} requires Node-API version ${moduleApiVersion}, but this version of Node.js only supports version ${NODE_API_SUPPORTED_VERSION_MAX} add-ons.`; + throw new Error(errorMessage); +} +function handleThrow(envObject, value) { + if (envObject.terminatedOrTerminating()) { + return; + } + throw value; +} +class Env { + constructor(ctx, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort) { + this.ctx = ctx; + this.moduleApiVersion = moduleApiVersion; + this.makeDynCall_vppp = makeDynCall_vppp; + this.makeDynCall_vp = makeDynCall_vp; + this.abort = abort; + this.openHandleScopes = 0; + this.instanceData = null; + this.tryCatch = new TryCatch(); + this.refs = 1; + this.reflist = new RefTracker(); + this.finalizing_reflist = new RefTracker(); + this.pendingFinalizers = []; + this.lastError = { + errorCode: 0, + engineErrorCode: 0, + engineReserved: 0 + }; + this.inGcFinalizer = false; + this._bindingMap = new WeakMap(); + this.id = 0; + } + canCallIntoJs() { + return true; + } + terminatedOrTerminating() { + return !this.canCallIntoJs(); + } + ref() { + this.refs++; + } + unref() { + this.refs--; + if (this.refs === 0) { + this.dispose(); + } + } + ensureHandle(value) { + return this.ctx.ensureHandle(value); + } + ensureHandleId(value) { + return this.ensureHandle(value).id; + } + clearLastError() { + const lastError = this.lastError; + if (lastError.errorCode !== 0) + lastError.errorCode = 0; + if (lastError.engineErrorCode !== 0) + lastError.engineErrorCode = 0; + if (lastError.engineReserved !== 0) + lastError.engineReserved = 0; + return 0; + } + setLastError(error_code, engine_error_code = 0, engine_reserved = 0) { + const lastError = this.lastError; + if (lastError.errorCode !== error_code) + lastError.errorCode = error_code; + if (lastError.engineErrorCode !== engine_error_code) + lastError.engineErrorCode = engine_error_code; + if (lastError.engineReserved !== engine_reserved) + lastError.engineReserved = engine_reserved; + return error_code; + } + getReturnStatus() { + return !this.tryCatch.hasCaught() ? 0 : this.setLastError(10); + } + callIntoModule(fn, handleException = handleThrow) { + const openHandleScopesBefore = this.openHandleScopes; + this.clearLastError(); + const r = fn(this); + if (openHandleScopesBefore !== this.openHandleScopes) { + this.abort('open_handle_scopes != open_handle_scopes_before'); + } + if (this.tryCatch.hasCaught()) { + const err = this.tryCatch.extractException(); + handleException(this, err); + } + return r; + } + invokeFinalizerFromGC(finalizer) { + if (this.moduleApiVersion !== NAPI_VERSION_EXPERIMENTAL) { + this.enqueueFinalizer(finalizer); + } + else { + const saved = this.inGcFinalizer; + this.inGcFinalizer = true; + try { + finalizer.finalize(); + } + finally { + this.inGcFinalizer = saved; + } + } + } + checkGCAccess() { + if (this.moduleApiVersion === NAPI_VERSION_EXPERIMENTAL && this.inGcFinalizer) { + this.abort('Finalizer is calling a function that may affect GC state.\n' + + 'The finalizers are run directly from GC and must not affect GC ' + + 'state.\n' + + 'Use `node_api_post_finalizer` from inside of the finalizer to work ' + + 'around this issue.\n' + + 'It schedules the call as a new task in the event loop.'); + } + } + enqueueFinalizer(finalizer) { + if (this.pendingFinalizers.indexOf(finalizer) === -1) { + this.pendingFinalizers.push(finalizer); + } + } + dequeueFinalizer(finalizer) { + const index = this.pendingFinalizers.indexOf(finalizer); + if (index !== -1) { + this.pendingFinalizers.splice(index, 1); + } + } + deleteMe() { + RefTracker.finalizeAll(this.finalizing_reflist); + RefTracker.finalizeAll(this.reflist); + this.tryCatch.extractException(); + this.ctx.envStore.remove(this.id); + } + dispose() { + if (this.id === 0) + return; + this.deleteMe(); + this.finalizing_reflist.dispose(); + this.reflist.dispose(); + this.id = 0; + } + initObjectBinding(value) { + const binding = { + wrapped: 0, + tag: null + }; + this._bindingMap.set(value, binding); + return binding; + } + getObjectBinding(value) { + if (this._bindingMap.has(value)) { + return this._bindingMap.get(value); + } + return this.initObjectBinding(value); + } + setInstanceData(data, finalize_cb, finalize_hint) { + if (this.instanceData) { + this.instanceData.dispose(); + } + this.instanceData = TrackedFinalizer.create(this, finalize_cb, data, finalize_hint); + } + getInstanceData() { + return this.instanceData ? this.instanceData.data() : 0; + } +} +class NodeEnv extends Env { + constructor(ctx, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding) { + super(ctx, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort); + this.filename = filename; + this.nodeBinding = nodeBinding; + this.destructing = false; + this.finalizationScheduled = false; + } + deleteMe() { + this.destructing = true; + this.drainFinalizerQueue(); + super.deleteMe(); + } + canCallIntoJs() { + return super.canCallIntoJs() && this.ctx.canCallIntoJs(); + } + triggerFatalException(err) { + if (this.nodeBinding) { + this.nodeBinding.napi.fatalException(err); + } + else { + if (typeof process === 'object' && process !== null && typeof process._fatalException === 'function') { + const handled = process._fatalException(err); + if (!handled) { + console.error(err); + process.exit(1); + } + } + else { + throw err; + } + } + } + callbackIntoModule(enforceUncaughtExceptionPolicy, fn) { + return this.callIntoModule(fn, (envObject, err) => { + if (envObject.terminatedOrTerminating()) { + return; + } + const hasProcess = typeof process === 'object' && process !== null; + const hasForceFlag = hasProcess ? Boolean(process.execArgv && (process.execArgv.indexOf('--force-node-api-uncaught-exceptions-policy') !== -1)) : false; + if (envObject.moduleApiVersion < 10 && !hasForceFlag && !enforceUncaughtExceptionPolicy) { + const warn = hasProcess && typeof process.emitWarning === 'function' + ? process.emitWarning + : function (warning, type, code) { + if (warning instanceof Error) { + console.warn(warning.toString()); + } + else { + const prefix = code ? `[${code}] ` : ''; + console.warn(`${prefix}${type || 'Warning'}: ${warning}`); + } + }; + warn('Uncaught Node-API callback exception detected, please run node with option --force-node-api-uncaught-exceptions-policy=true to handle those exceptions properly.', 'DeprecationWarning', 'DEP0168'); + return; + } + envObject.triggerFatalException(err); + }); + } + callFinalizer(cb, data, hint) { + this.callFinalizerInternal(1, cb, data, hint); + } + callFinalizerInternal(forceUncaught, cb, data, hint) { + const f = this.makeDynCall_vppp(cb); + const env = this.id; + const scope = this.ctx.openScope(this); + try { + this.callbackIntoModule(Boolean(forceUncaught), () => { f(env, data, hint); }); + } + finally { + this.ctx.closeScope(this, scope); + } + } + enqueueFinalizer(finalizer) { + super.enqueueFinalizer(finalizer); + if (!this.finalizationScheduled && !this.destructing) { + this.finalizationScheduled = true; + this.ref(); + _setImmediate(() => { + this.finalizationScheduled = false; + this.unref(); + this.drainFinalizerQueue(); + }); + } + } + drainFinalizerQueue() { + while (this.pendingFinalizers.length > 0) { + const refTracker = this.pendingFinalizers.shift(); + refTracker.finalize(); + } + } +} +function newEnv(ctx, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding) { + moduleApiVersion = typeof moduleApiVersion !== 'number' ? NODE_API_DEFAULT_MODULE_API_VERSION : moduleApiVersion; + if (moduleApiVersion < NODE_API_DEFAULT_MODULE_API_VERSION) { + moduleApiVersion = NODE_API_DEFAULT_MODULE_API_VERSION; + } + else if (moduleApiVersion > NODE_API_SUPPORTED_VERSION_MAX && moduleApiVersion !== NAPI_VERSION_EXPERIMENTAL) { + throwNodeApiVersionError(filename, moduleApiVersion); + } + const env = new NodeEnv(ctx, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding); + ctx.envStore.add(env); + ctx.addCleanupHook(env, () => { env.unref(); }, 0); + return env; +} + +class EmnapiError extends Error { + constructor(message) { + super(message); + const ErrorConstructor = new.target; + const proto = ErrorConstructor.prototype; + if (!(this instanceof EmnapiError)) { + const setPrototypeOf = Object.setPrototypeOf; + if (typeof setPrototypeOf === 'function') { + setPrototypeOf.call(Object, this, proto); + } + else { + this.__proto__ = proto; + } + if (typeof Error.captureStackTrace === 'function') { + Error.captureStackTrace(this, ErrorConstructor); + } + } + } +} +Object.defineProperty(EmnapiError.prototype, 'name', { + configurable: true, + writable: true, + value: 'EmnapiError' +}); +class NotSupportWeakRefError extends EmnapiError { + constructor(api, message) { + super(`${api}: The current runtime does not support "FinalizationRegistry" and "WeakRef".${message ? ` ${message}` : ''}`); + } +} +Object.defineProperty(NotSupportWeakRefError.prototype, 'name', { + configurable: true, + writable: true, + value: 'NotSupportWeakRefError' +}); +class NotSupportBufferError extends EmnapiError { + constructor(api, message) { + super(`${api}: The current runtime does not support "Buffer". Consider using buffer polyfill to make sure \`globalThis.Buffer\` is defined.${message ? ` ${message}` : ''}`); + } +} +Object.defineProperty(NotSupportBufferError.prototype, 'name', { + configurable: true, + writable: true, + value: 'NotSupportBufferError' +}); + +class StrongRef { + constructor(value) { + this._value = value; + } + deref() { + return this._value; + } + dispose() { + this._value = undefined; + } +} +class Persistent { + constructor(value) { + this._ref = new StrongRef(value); + } + setWeak(param, callback) { + if (!supportFinalizer || this._ref === undefined || this._ref instanceof WeakRef) + return; + const value = this._ref.deref(); + try { + Persistent._registry.register(value, this, this); + const weakRef = new WeakRef(value); + this._ref.dispose(); + this._ref = weakRef; + this._param = param; + this._callback = callback; + } + catch (err) { + if (typeof value === 'symbol') ; + else { + throw err; + } + } + } + clearWeak() { + if (!supportFinalizer || this._ref === undefined) + return; + if (this._ref instanceof WeakRef) { + try { + Persistent._registry.unregister(this); + } + catch (_) { } + this._param = undefined; + this._callback = undefined; + const value = this._ref.deref(); + if (value === undefined) { + this._ref = value; + } + else { + this._ref = new StrongRef(value); + } + } + } + reset() { + if (supportFinalizer) { + try { + Persistent._registry.unregister(this); + } + catch (_) { } + } + this._param = undefined; + this._callback = undefined; + if (this._ref instanceof StrongRef) { + this._ref.dispose(); + } + this._ref = undefined; + } + isEmpty() { + return this._ref === undefined; + } + deref() { + if (this._ref === undefined) + return undefined; + return this._ref.deref(); + } +} +Persistent._registry = supportFinalizer + ? new FinalizationRegistry((value) => { + value._ref = undefined; + const callback = value._callback; + const param = value._param; + value._callback = undefined; + value._param = undefined; + if (typeof callback === 'function') { + callback(param); + } + }) + : undefined; + +var ReferenceOwnership; +(function (ReferenceOwnership) { + ReferenceOwnership[ReferenceOwnership["kRuntime"] = 0] = "kRuntime"; + ReferenceOwnership[ReferenceOwnership["kUserland"] = 1] = "kUserland"; +})(ReferenceOwnership || (ReferenceOwnership = {})); +function canBeHeldWeakly(value) { + return value.isObject() || value.isFunction() || value.isSymbol(); +} +class Reference extends RefTracker { + static weakCallback(ref) { + ref.persistent.reset(); + ref.invokeFinalizerFromGC(); + } + static create(envObject, handle_id, initialRefcount, ownership, _unused1, _unused2, _unused3) { + const ref = new Reference(envObject, handle_id, initialRefcount, ownership); + envObject.ctx.refStore.add(ref); + ref.link(envObject.reflist); + return ref; + } + constructor(envObject, handle_id, initialRefcount, ownership) { + super(); + this.envObject = envObject; + this._refcount = initialRefcount; + this._ownership = ownership; + const handle = envObject.ctx.handleStore.get(handle_id); + this.canBeWeak = canBeHeldWeakly(handle); + this.persistent = new Persistent(handle.value); + this.id = 0; + if (initialRefcount === 0) { + this._setWeak(); + } + } + ref() { + if (this.persistent.isEmpty()) { + return 0; + } + if (++this._refcount === 1 && this.canBeWeak) { + this.persistent.clearWeak(); + } + return this._refcount; + } + unref() { + if (this.persistent.isEmpty() || this._refcount === 0) { + return 0; + } + if (--this._refcount === 0) { + this._setWeak(); + } + return this._refcount; + } + get(envObject = this.envObject) { + if (this.persistent.isEmpty()) { + return 0; + } + const obj = this.persistent.deref(); + const handle = envObject.ensureHandle(obj); + return handle.id; + } + resetFinalizer() { } + data() { return 0; } + refcount() { return this._refcount; } + ownership() { return this._ownership; } + callUserFinalizer() { } + invokeFinalizerFromGC() { + this.finalize(); + } + _setWeak() { + if (this.canBeWeak) { + this.persistent.setWeak(this, Reference.weakCallback); + } + else { + this.persistent.reset(); + } + } + finalize() { + this.persistent.reset(); + const deleteMe = this._ownership === ReferenceOwnership.kRuntime; + this.unlink(); + this.callUserFinalizer(); + if (deleteMe) { + this.dispose(); + } + } + dispose() { + if (this.id === 0) + return; + this.unlink(); + this.persistent.reset(); + this.envObject.ctx.refStore.remove(this.id); + super.dispose(); + this.envObject = undefined; + this.id = 0; + } +} +class ReferenceWithData extends Reference { + static create(envObject, value, initialRefcount, ownership, data) { + const reference = new ReferenceWithData(envObject, value, initialRefcount, ownership, data); + envObject.ctx.refStore.add(reference); + reference.link(envObject.reflist); + return reference; + } + constructor(envObject, value, initialRefcount, ownership, _data) { + super(envObject, value, initialRefcount, ownership); + this._data = _data; + } + data() { + return this._data; + } +} +class ReferenceWithFinalizer extends Reference { + static create(envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint) { + const reference = new ReferenceWithFinalizer(envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint); + envObject.ctx.refStore.add(reference); + reference.link(envObject.finalizing_reflist); + return reference; + } + constructor(envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint) { + super(envObject, value, initialRefcount, ownership); + this._finalizer = new Finalizer(envObject, finalize_callback, finalize_data, finalize_hint); + } + resetFinalizer() { + this._finalizer.resetFinalizer(); + } + data() { + return this._finalizer.data(); + } + callUserFinalizer() { + this._finalizer.callFinalizer(); + } + invokeFinalizerFromGC() { + this._finalizer.envObject.invokeFinalizerFromGC(this); + } + dispose() { + if (!this._finalizer) + return; + this._finalizer.envObject.dequeueFinalizer(this); + this._finalizer.dispose(); + super.dispose(); + this._finalizer = undefined; + } +} + +class Deferred { + static create(ctx, value) { + const deferred = new Deferred(ctx, value); + ctx.deferredStore.add(deferred); + return deferred; + } + constructor(ctx, value) { + Object.defineProperties(this, { + id: { + configurable: true, + enumerable: true, + value: 0, + writable: true + }, + ctx: { + configurable: true, + enumerable: true, + value: ctx, + writable: true + }, + value: { + configurable: true, + enumerable: true, + value, + writable: true + } + }); + } + resolve(value) { + this.value.resolve(value); + this.dispose(); + } + reject(reason) { + this.value.reject(reason); + this.dispose(); + } + dispose() { + this.ctx.deferredStore.remove(this.id); + this.id = 0; + this.value = null; + this.ctx = null; + } +} + +class Store { + constructor() { + this._values = [undefined]; + this._values.length = 4; + this._size = 1; + this._freeList = []; + } + add(value) { + let id; + if (this._freeList.length) { + id = this._freeList.shift(); + } + else { + id = this._size; + this._size++; + const capacity = this._values.length; + if (id >= capacity) { + this._values.length = capacity + (capacity >> 1) + 16; + } + } + value.id = id; + this._values[id] = value; + } + get(id) { + return this._values[id]; + } + has(id) { + return this._values[id] !== undefined; + } + remove(id) { + const value = this._values[id]; + if (value) { + value.id = 0; + this._values[id] = undefined; + this._freeList.push(Number(id)); + } + } + dispose() { + for (let i = 1; i < this._size; ++i) { + const value = this._values[i]; + value === null || value === void 0 ? void 0 : value.dispose(); + } + this._values = [undefined]; + this._size = 1; + this._freeList = []; + } +} + +const kMaxReasonableBytes = BigInt(1) << BigInt(60); +const kMinReasonableBytes = -kMaxReasonableBytes; +class ExternalMemory { + constructor(onChange) { + this.total = BigInt(0); + this.onChange = onChange !== null && onChange !== void 0 ? onChange : null; + } + adjust(changeInBytes) { + changeInBytes = BigInt(changeInBytes); + if (!(kMinReasonableBytes <= changeInBytes && changeInBytes < kMaxReasonableBytes)) { + throw new RangeError(`changeInBytes ${changeInBytes} is out of reasonable range`); + } + const old = this.total; + this.total += changeInBytes; + const amount = this.total; + const onChange = this.onChange; + if (changeInBytes) { + onChange === null || onChange === void 0 ? void 0 : onChange(amount, old, changeInBytes); + } + return amount; + } +} + +class CleanupHookCallback { + constructor(envObject, fn, arg, order) { + this.envObject = envObject; + this.fn = fn; + this.arg = arg; + this.order = order; + } +} +class CleanupQueue { + constructor() { + this._cleanupHooks = []; + this._cleanupHookCounter = 0; + } + empty() { + return this._cleanupHooks.length === 0; + } + add(envObject, fn, arg) { + if (this._cleanupHooks.filter((hook) => (hook.envObject === envObject && hook.fn === fn && hook.arg === arg)).length > 0) { + throw new Error('Can not add same fn and arg twice'); + } + this._cleanupHooks.push(new CleanupHookCallback(envObject, fn, arg, this._cleanupHookCounter++)); + } + remove(envObject, fn, arg) { + for (let i = 0; i < this._cleanupHooks.length; ++i) { + const hook = this._cleanupHooks[i]; + if (hook.envObject === envObject && hook.fn === fn && hook.arg === arg) { + this._cleanupHooks.splice(i, 1); + return; + } + } + } + drain() { + const hooks = this._cleanupHooks.slice(); + hooks.sort((a, b) => (b.order - a.order)); + for (let i = 0; i < hooks.length; ++i) { + const cb = hooks[i]; + if (typeof cb.fn === 'number') { + cb.envObject.makeDynCall_vp(cb.fn)(cb.arg); + } + else { + cb.fn(cb.arg); + } + this._cleanupHooks.splice(this._cleanupHooks.indexOf(cb), 1); + } + } + dispose() { + this._cleanupHooks.length = 0; + this._cleanupHookCounter = 0; + } +} +class NodejsWaitingRequestCounter { + constructor() { + this.refHandle = new _MessageChannel().port1; + this.count = 0; + } + increase() { + if (this.count === 0) { + if (this.refHandle.ref) { + this.refHandle.ref(); + } + } + this.count++; + } + decrease() { + if (this.count === 0) + return; + if (this.count === 1) { + if (this.refHandle.unref) { + this.refHandle.unref(); + } + } + this.count--; + } +} +class Context { + constructor(options) { + this._isStopping = false; + this._canCallIntoJs = true; + this._suppressDestroy = false; + this.envStore = new Store(); + this.scopeStore = new ScopeStore(); + this.refStore = new Store(); + this.deferredStore = new Store(); + this.handleStore = new HandleStore(); + this.feature = { + supportReflect, + supportFinalizer, + supportWeakSymbol, + supportBigInt, + supportNewFunction, + canSetFunctionName, + setImmediate: _setImmediate, + Buffer: _Buffer, + MessageChannel: _MessageChannel + }; + this.cleanupQueue = new CleanupQueue(); + this._externalMemory = new ExternalMemory(options === null || options === void 0 ? void 0 : options.onExternalMemoryChange); + if (typeof process === 'object' && process !== null && typeof process.once === 'function') { + this.refCounter = new NodejsWaitingRequestCounter(); + process.once('beforeExit', () => { + if (!this._suppressDestroy) { + this.destroy(); + } + }); + } + } + suppressDestroy() { + this._suppressDestroy = true; + } + getRuntimeVersions() { + return { + version, + NODE_API_SUPPORTED_VERSION_MAX, + NAPI_VERSION_EXPERIMENTAL, + NODE_API_DEFAULT_MODULE_API_VERSION + }; + } + createNotSupportWeakRefError(api, message) { + return new NotSupportWeakRefError(api, message); + } + createNotSupportBufferError(api, message) { + return new NotSupportBufferError(api, message); + } + createReference(envObject, handle_id, initialRefcount, ownership) { + return Reference.create(envObject, handle_id, initialRefcount, ownership); + } + createReferenceWithData(envObject, handle_id, initialRefcount, ownership, data) { + return ReferenceWithData.create(envObject, handle_id, initialRefcount, ownership, data); + } + createReferenceWithFinalizer(envObject, handle_id, initialRefcount, ownership, finalize_callback = 0, finalize_data = 0, finalize_hint = 0) { + return ReferenceWithFinalizer.create(envObject, handle_id, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint); + } + createDeferred(value) { + return Deferred.create(this, value); + } + adjustAmountOfExternalAllocatedMemory(changeInBytes) { + return this._externalMemory.adjust(changeInBytes); + } + createEnv(filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding) { + return newEnv(this, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding); + } + createTrackedFinalizer(envObject, finalize_callback, finalize_data, finalize_hint) { + return TrackedFinalizer.create(envObject, finalize_callback, finalize_data, finalize_hint); + } + getCurrentScope() { + return this.scopeStore.currentScope; + } + addToCurrentScope(value) { + return this.scopeStore.currentScope.add(value); + } + openScope(envObject) { + const scope = this.scopeStore.openScope(this.handleStore); + if (envObject) + envObject.openHandleScopes++; + return scope; + } + closeScope(envObject, _scope) { + if (envObject && envObject.openHandleScopes === 0) + return; + this.scopeStore.closeScope(); + if (envObject) + envObject.openHandleScopes--; + } + ensureHandle(value) { + switch (value) { + case undefined: return HandleStore.UNDEFINED; + case null: return HandleStore.NULL; + case true: return HandleStore.TRUE; + case false: return HandleStore.FALSE; + case _global: return HandleStore.GLOBAL; + } + return this.addToCurrentScope(value); + } + addCleanupHook(envObject, fn, arg) { + this.cleanupQueue.add(envObject, fn, arg); + } + removeCleanupHook(envObject, fn, arg) { + this.cleanupQueue.remove(envObject, fn, arg); + } + runCleanup() { + while (!this.cleanupQueue.empty()) { + this.cleanupQueue.drain(); + } + } + increaseWaitingRequestCounter() { + var _a; + (_a = this.refCounter) === null || _a === void 0 ? void 0 : _a.increase(); + } + decreaseWaitingRequestCounter() { + var _a; + (_a = this.refCounter) === null || _a === void 0 ? void 0 : _a.decrease(); + } + setCanCallIntoJs(value) { + this._canCallIntoJs = value; + } + setStopping(value) { + this._isStopping = value; + } + canCallIntoJs() { + return this._canCallIntoJs && !this._isStopping; + } + destroy() { + this.setStopping(true); + this.setCanCallIntoJs(false); + this.runCleanup(); + } +} +let defaultContext; +function createContext(options) { + return new Context(options); +} +function getDefaultContext() { + if (!defaultContext) { + defaultContext = createContext(); + } + return defaultContext; +} + +export { ConstHandle, Context, Deferred, EmnapiError, Env, External, Finalizer, Handle, HandleScope, HandleStore, NAPI_VERSION_EXPERIMENTAL, NODE_API_DEFAULT_MODULE_API_VERSION, NODE_API_SUPPORTED_VERSION_MAX, NODE_API_SUPPORTED_VERSION_MIN, NodeEnv, NotSupportBufferError, NotSupportWeakRefError, Persistent, RefTracker, Reference, ReferenceOwnership, ReferenceWithData, ReferenceWithFinalizer, ScopeStore, Store, TrackedFinalizer, TryCatch, createContext, getDefaultContext, getExternalValue, isExternal, isReferenceType, version }; diff --git a/node_modules/@emnapi/runtime/index.js b/node_modules/@emnapi/runtime/index.js new file mode 100644 index 0000000..efd0f2f --- /dev/null +++ b/node_modules/@emnapi/runtime/index.js @@ -0,0 +1,5 @@ +if (typeof process !== 'undefined' && process.env.NODE_ENV === 'production') { + module.exports = require('./dist/emnapi.cjs.min.js') +} else { + module.exports = require('./dist/emnapi.cjs.js') +} diff --git a/node_modules/@emnapi/runtime/package.json b/node_modules/@emnapi/runtime/package.json new file mode 100644 index 0000000..f0cbd77 --- /dev/null +++ b/node_modules/@emnapi/runtime/package.json @@ -0,0 +1,48 @@ +{ + "name": "@emnapi/runtime", + "version": "1.11.3", + "description": "emnapi runtime", + "main": "index.js", + "module": "./dist/emnapi.esm-bundler.js", + "types": "./dist/emnapi.d.ts", + "sideEffects": false, + "exports": { + ".": { + "types": { + "module": "./dist/emnapi.d.ts", + "import": "./dist/emnapi.d.mts", + "default": "./dist/emnapi.d.ts" + }, + "module": "./dist/emnapi.esm-bundler.js", + "import": "./dist/emnapi.mjs", + "default": "./index.js" + }, + "./dist/emnapi.cjs.min": { + "types": "./dist/emnapi.d.ts", + "default": "./dist/emnapi.cjs.min.js" + }, + "./dist/emnapi.min.mjs": { + "types": "./dist/emnapi.d.mts", + "default": "./dist/emnapi.min.mjs" + } + }, + "dependencies": { + "tslib": "^2.4.0" + }, + "scripts": { + "build": "node ./script/build.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/toyobayashi/emnapi.git" + }, + "author": "toyobayashi", + "license": "MIT", + "bugs": { + "url": "https://github.com/toyobayashi/emnapi/issues" + }, + "homepage": "https://github.com/toyobayashi/emnapi#readme", + "publishConfig": { + "access": "public" + } +} diff --git a/node_modules/@img/colour/LICENSE.md b/node_modules/@img/colour/LICENSE.md new file mode 100644 index 0000000..292c550 --- /dev/null +++ b/node_modules/@img/colour/LICENSE.md @@ -0,0 +1,82 @@ +# Licensing + +## color + +Copyright (c) 2012 Heather Arthur + +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. + +## color-convert + +Copyright (c) 2011-2016 Heather Arthur . +Copyright (c) 2016-2021 Josh Junon . + +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. + +## color-string + +Copyright (c) 2011 Heather Arthur + +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. + +## color-name + +The MIT License (MIT) +Copyright (c) 2015 Dmitry Ivanov + +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. diff --git a/node_modules/@img/colour/README.md b/node_modules/@img/colour/README.md new file mode 100644 index 0000000..a33e4eb --- /dev/null +++ b/node_modules/@img/colour/README.md @@ -0,0 +1,15 @@ +# `@img/colour` + +The latest version of the +[color](https://www.npmjs.com/package/color) +package is now ESM-only, +however some JavaScript runtimes do not yet support this, +which includes versions of Node.js prior to 20.19.0. + +This package converts the `color` package and its dependencies, +all of which are MIT-licensed, to CommonJS. + +- [color](https://www.npmjs.com/package/color) +- [color-convert](https://www.npmjs.com/package/color-convert) +- [color-string](https://www.npmjs.com/package/color-string) +- [color-name](https://www.npmjs.com/package/color-name) diff --git a/node_modules/@img/colour/color.cjs b/node_modules/@img/colour/color.cjs new file mode 100644 index 0000000..d5b7ee2 --- /dev/null +++ b/node_modules/@img/colour/color.cjs @@ -0,0 +1,1596 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// node_modules/color/index.js +var index_exports = {}; +__export(index_exports, { + default: () => index_default +}); +module.exports = __toCommonJS(index_exports); + +// node_modules/color-name/index.js +var colors = { + aliceblue: [240, 248, 255], + antiquewhite: [250, 235, 215], + aqua: [0, 255, 255], + aquamarine: [127, 255, 212], + azure: [240, 255, 255], + beige: [245, 245, 220], + bisque: [255, 228, 196], + black: [0, 0, 0], + blanchedalmond: [255, 235, 205], + blue: [0, 0, 255], + blueviolet: [138, 43, 226], + brown: [165, 42, 42], + burlywood: [222, 184, 135], + cadetblue: [95, 158, 160], + chartreuse: [127, 255, 0], + chocolate: [210, 105, 30], + coral: [255, 127, 80], + cornflowerblue: [100, 149, 237], + cornsilk: [255, 248, 220], + crimson: [220, 20, 60], + cyan: [0, 255, 255], + darkblue: [0, 0, 139], + darkcyan: [0, 139, 139], + darkgoldenrod: [184, 134, 11], + darkgray: [169, 169, 169], + darkgreen: [0, 100, 0], + darkgrey: [169, 169, 169], + darkkhaki: [189, 183, 107], + darkmagenta: [139, 0, 139], + darkolivegreen: [85, 107, 47], + darkorange: [255, 140, 0], + darkorchid: [153, 50, 204], + darkred: [139, 0, 0], + darksalmon: [233, 150, 122], + darkseagreen: [143, 188, 143], + darkslateblue: [72, 61, 139], + darkslategray: [47, 79, 79], + darkslategrey: [47, 79, 79], + darkturquoise: [0, 206, 209], + darkviolet: [148, 0, 211], + deeppink: [255, 20, 147], + deepskyblue: [0, 191, 255], + dimgray: [105, 105, 105], + dimgrey: [105, 105, 105], + dodgerblue: [30, 144, 255], + firebrick: [178, 34, 34], + floralwhite: [255, 250, 240], + forestgreen: [34, 139, 34], + fuchsia: [255, 0, 255], + gainsboro: [220, 220, 220], + ghostwhite: [248, 248, 255], + gold: [255, 215, 0], + goldenrod: [218, 165, 32], + gray: [128, 128, 128], + green: [0, 128, 0], + greenyellow: [173, 255, 47], + grey: [128, 128, 128], + honeydew: [240, 255, 240], + hotpink: [255, 105, 180], + indianred: [205, 92, 92], + indigo: [75, 0, 130], + ivory: [255, 255, 240], + khaki: [240, 230, 140], + lavender: [230, 230, 250], + lavenderblush: [255, 240, 245], + lawngreen: [124, 252, 0], + lemonchiffon: [255, 250, 205], + lightblue: [173, 216, 230], + lightcoral: [240, 128, 128], + lightcyan: [224, 255, 255], + lightgoldenrodyellow: [250, 250, 210], + lightgray: [211, 211, 211], + lightgreen: [144, 238, 144], + lightgrey: [211, 211, 211], + lightpink: [255, 182, 193], + lightsalmon: [255, 160, 122], + lightseagreen: [32, 178, 170], + lightskyblue: [135, 206, 250], + lightslategray: [119, 136, 153], + lightslategrey: [119, 136, 153], + lightsteelblue: [176, 196, 222], + lightyellow: [255, 255, 224], + lime: [0, 255, 0], + limegreen: [50, 205, 50], + linen: [250, 240, 230], + magenta: [255, 0, 255], + maroon: [128, 0, 0], + mediumaquamarine: [102, 205, 170], + mediumblue: [0, 0, 205], + mediumorchid: [186, 85, 211], + mediumpurple: [147, 112, 219], + mediumseagreen: [60, 179, 113], + mediumslateblue: [123, 104, 238], + mediumspringgreen: [0, 250, 154], + mediumturquoise: [72, 209, 204], + mediumvioletred: [199, 21, 133], + midnightblue: [25, 25, 112], + mintcream: [245, 255, 250], + mistyrose: [255, 228, 225], + moccasin: [255, 228, 181], + navajowhite: [255, 222, 173], + navy: [0, 0, 128], + oldlace: [253, 245, 230], + olive: [128, 128, 0], + olivedrab: [107, 142, 35], + orange: [255, 165, 0], + orangered: [255, 69, 0], + orchid: [218, 112, 214], + palegoldenrod: [238, 232, 170], + palegreen: [152, 251, 152], + paleturquoise: [175, 238, 238], + palevioletred: [219, 112, 147], + papayawhip: [255, 239, 213], + peachpuff: [255, 218, 185], + peru: [205, 133, 63], + pink: [255, 192, 203], + plum: [221, 160, 221], + powderblue: [176, 224, 230], + purple: [128, 0, 128], + rebeccapurple: [102, 51, 153], + red: [255, 0, 0], + rosybrown: [188, 143, 143], + royalblue: [65, 105, 225], + saddlebrown: [139, 69, 19], + salmon: [250, 128, 114], + sandybrown: [244, 164, 96], + seagreen: [46, 139, 87], + seashell: [255, 245, 238], + sienna: [160, 82, 45], + silver: [192, 192, 192], + skyblue: [135, 206, 235], + slateblue: [106, 90, 205], + slategray: [112, 128, 144], + slategrey: [112, 128, 144], + snow: [255, 250, 250], + springgreen: [0, 255, 127], + steelblue: [70, 130, 180], + tan: [210, 180, 140], + teal: [0, 128, 128], + thistle: [216, 191, 216], + tomato: [255, 99, 71], + turquoise: [64, 224, 208], + violet: [238, 130, 238], + wheat: [245, 222, 179], + white: [255, 255, 255], + whitesmoke: [245, 245, 245], + yellow: [255, 255, 0], + yellowgreen: [154, 205, 50] +}; +for (const key in colors) Object.freeze(colors[key]); +var color_name_default = Object.freeze(colors); + +// node_modules/color-string/index.js +var reverseNames = /* @__PURE__ */ Object.create(null); +for (const name in color_name_default) { + if (Object.hasOwn(color_name_default, name)) { + reverseNames[color_name_default[name]] = name; + } +} +var cs = { + to: {}, + get: {} +}; +cs.get = function(string) { + const prefix = string.slice(0, 3).toLowerCase(); + let value; + let model; + switch (prefix) { + case "hsl": { + value = cs.get.hsl(string); + model = "hsl"; + break; + } + case "hwb": { + value = cs.get.hwb(string); + model = "hwb"; + break; + } + default: { + value = cs.get.rgb(string); + model = "rgb"; + break; + } + } + if (!value) { + return null; + } + return { model, value }; +}; +cs.get.rgb = function(string) { + if (!string) { + return null; + } + const abbr = /^#([a-f\d]{3,4})$/i; + const hex = /^#([a-f\d]{6})([a-f\d]{2})?$/i; + const rgba = /^rgba?\(\s*([+-]?(?:\d*\.)?\d+(?:e\d+)?)(?=[\s,])\s*(?:,\s*)?([+-]?(?:\d*\.)?\d+(?:e\d+)?)(?=[\s,])\s*(?:,\s*)?([+-]?(?:\d*\.)?\d+(?:e\d+)?)\s*(?:[\s,|/]\s*([+-]?(?:\d*\.)?\d+(?:e\d+)?)(%?)\s*)?\)$/i; + const per = /^rgba?\(\s*([+-]?[\d.]+)%\s*,?\s*([+-]?[\d.]+)%\s*,?\s*([+-]?[\d.]+)%\s*(?:[\s,|/]\s*([+-]?[\d.]+)(%?)\s*)?\)$/i; + const keyword = /^(\w+)$/; + let rgb = [0, 0, 0, 1]; + let match; + let i; + let hexAlpha; + if (match = string.match(hex)) { + hexAlpha = match[2]; + match = match[1]; + for (i = 0; i < 3; i++) { + const i2 = i * 2; + rgb[i] = Number.parseInt(match.slice(i2, i2 + 2), 16); + } + if (hexAlpha) { + rgb[3] = Number.parseInt(hexAlpha, 16) / 255; + } + } else if (match = string.match(abbr)) { + match = match[1]; + hexAlpha = match[3]; + for (i = 0; i < 3; i++) { + rgb[i] = Number.parseInt(match[i] + match[i], 16); + } + if (hexAlpha) { + rgb[3] = Number.parseInt(hexAlpha + hexAlpha, 16) / 255; + } + } else if (match = string.match(rgba)) { + for (i = 0; i < 3; i++) { + rgb[i] = Number.parseFloat(match[i + 1]); + } + if (match[4]) { + rgb[3] = match[5] ? Number.parseFloat(match[4]) * 0.01 : Number.parseFloat(match[4]); + } + } else if (match = string.match(per)) { + for (i = 0; i < 3; i++) { + rgb[i] = Math.round(Number.parseFloat(match[i + 1]) * 2.55); + } + if (match[4]) { + rgb[3] = match[5] ? Number.parseFloat(match[4]) * 0.01 : Number.parseFloat(match[4]); + } + } else if (match = string.toLowerCase().match(keyword)) { + if (match[1] === "transparent") { + return [0, 0, 0, 0]; + } + if (!Object.hasOwn(color_name_default, match[1])) { + return null; + } + rgb = color_name_default[match[1]].slice(); + rgb[3] = 1; + return rgb; + } else { + return null; + } + for (i = 0; i < 3; i++) { + rgb[i] = clamp(rgb[i], 0, 255); + } + rgb[3] = clamp(rgb[3], 0, 1); + return rgb; +}; +cs.get.hsl = function(string) { + if (!string) { + return null; + } + const hsl = /^hsla?\(\s*([+-]?(?:\d{0,3}\.)?\d+)(?:deg)?\s*,?\s*([+-]?[\d.]+)%\s*,?\s*([+-]?[\d.]+)%\s*(?:[,|/]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:e[+-]?\d+)?)\s*)?\)$/i; + const match = string.match(hsl); + if (match) { + const alpha = Number.parseFloat(match[4]); + const h = (Number.parseFloat(match[1]) % 360 + 360) % 360; + const s = clamp(Number.parseFloat(match[2]), 0, 100); + const l = clamp(Number.parseFloat(match[3]), 0, 100); + const a = clamp(Number.isNaN(alpha) ? 1 : alpha, 0, 1); + return [h, s, l, a]; + } + return null; +}; +cs.get.hwb = function(string) { + if (!string) { + return null; + } + const hwb = /^hwb\(\s*([+-]?\d{0,3}(?:\.\d+)?)(?:deg)?\s*[\s,]\s*([+-]?[\d.]+)%\s*[\s,]\s*([+-]?[\d.]+)%\s*(?:[\s,]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:e[+-]?\d+)?)\s*)?\)$/i; + const match = string.match(hwb); + if (match) { + const alpha = Number.parseFloat(match[4]); + const h = (Number.parseFloat(match[1]) % 360 + 360) % 360; + const w = clamp(Number.parseFloat(match[2]), 0, 100); + const b = clamp(Number.parseFloat(match[3]), 0, 100); + const a = clamp(Number.isNaN(alpha) ? 1 : alpha, 0, 1); + return [h, w, b, a]; + } + return null; +}; +cs.to.hex = function(...rgba) { + return "#" + hexDouble(rgba[0]) + hexDouble(rgba[1]) + hexDouble(rgba[2]) + (rgba[3] < 1 ? hexDouble(Math.round(rgba[3] * 255)) : ""); +}; +cs.to.rgb = function(...rgba) { + return rgba.length < 4 || rgba[3] === 1 ? "rgb(" + Math.round(rgba[0]) + ", " + Math.round(rgba[1]) + ", " + Math.round(rgba[2]) + ")" : "rgba(" + Math.round(rgba[0]) + ", " + Math.round(rgba[1]) + ", " + Math.round(rgba[2]) + ", " + rgba[3] + ")"; +}; +cs.to.rgb.percent = function(...rgba) { + const r = Math.round(rgba[0] / 255 * 100); + const g = Math.round(rgba[1] / 255 * 100); + const b = Math.round(rgba[2] / 255 * 100); + return rgba.length < 4 || rgba[3] === 1 ? "rgb(" + r + "%, " + g + "%, " + b + "%)" : "rgba(" + r + "%, " + g + "%, " + b + "%, " + rgba[3] + ")"; +}; +cs.to.hsl = function(...hsla) { + return hsla.length < 4 || hsla[3] === 1 ? "hsl(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%)" : "hsla(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%, " + hsla[3] + ")"; +}; +cs.to.hwb = function(...hwba) { + let a = ""; + if (hwba.length >= 4 && hwba[3] !== 1) { + a = ", " + hwba[3]; + } + return "hwb(" + hwba[0] + ", " + hwba[1] + "%, " + hwba[2] + "%" + a + ")"; +}; +cs.to.keyword = function(...rgb) { + return reverseNames[rgb.slice(0, 3)]; +}; +function clamp(number_, min, max) { + return Math.min(Math.max(min, number_), max); +} +function hexDouble(number_) { + const string_ = Math.round(number_).toString(16).toUpperCase(); + return string_.length < 2 ? "0" + string_ : string_; +} +var color_string_default = cs; + +// node_modules/color-convert/conversions.js +var reverseKeywords = {}; +for (const key of Object.keys(color_name_default)) { + reverseKeywords[color_name_default[key]] = key; +} +var convert = { + rgb: { channels: 3, labels: "rgb" }, + hsl: { channels: 3, labels: "hsl" }, + hsv: { channels: 3, labels: "hsv" }, + hwb: { channels: 3, labels: "hwb" }, + cmyk: { channels: 4, labels: "cmyk" }, + xyz: { channels: 3, labels: "xyz" }, + lab: { channels: 3, labels: "lab" }, + oklab: { channels: 3, labels: ["okl", "oka", "okb"] }, + lch: { channels: 3, labels: "lch" }, + oklch: { channels: 3, labels: ["okl", "okc", "okh"] }, + hex: { channels: 1, labels: ["hex"] }, + keyword: { channels: 1, labels: ["keyword"] }, + ansi16: { channels: 1, labels: ["ansi16"] }, + ansi256: { channels: 1, labels: ["ansi256"] }, + hcg: { channels: 3, labels: ["h", "c", "g"] }, + apple: { channels: 3, labels: ["r16", "g16", "b16"] }, + gray: { channels: 1, labels: ["gray"] } +}; +var conversions_default = convert; +var LAB_FT = (6 / 29) ** 3; +function srgbNonlinearTransform(c) { + const cc = c > 31308e-7 ? 1.055 * c ** (1 / 2.4) - 0.055 : c * 12.92; + return Math.min(Math.max(0, cc), 1); +} +function srgbNonlinearTransformInv(c) { + return c > 0.04045 ? ((c + 0.055) / 1.055) ** 2.4 : c / 12.92; +} +for (const model of Object.keys(convert)) { + if (!("channels" in convert[model])) { + throw new Error("missing channels property: " + model); + } + if (!("labels" in convert[model])) { + throw new Error("missing channel labels property: " + model); + } + if (convert[model].labels.length !== convert[model].channels) { + throw new Error("channel and label counts mismatch: " + model); + } + const { channels, labels } = convert[model]; + delete convert[model].channels; + delete convert[model].labels; + Object.defineProperty(convert[model], "channels", { value: channels }); + Object.defineProperty(convert[model], "labels", { value: labels }); +} +convert.rgb.hsl = function(rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const min = Math.min(r, g, b); + const max = Math.max(r, g, b); + const delta = max - min; + let h; + let s; + switch (max) { + case min: { + h = 0; + break; + } + case r: { + h = (g - b) / delta; + break; + } + case g: { + h = 2 + (b - r) / delta; + break; + } + case b: { + h = 4 + (r - g) / delta; + break; + } + } + h = Math.min(h * 60, 360); + if (h < 0) { + h += 360; + } + const l = (min + max) / 2; + if (max === min) { + s = 0; + } else if (l <= 0.5) { + s = delta / (max + min); + } else { + s = delta / (2 - max - min); + } + return [h, s * 100, l * 100]; +}; +convert.rgb.hsv = function(rgb) { + let rdif; + let gdif; + let bdif; + let h; + let s; + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const v = Math.max(r, g, b); + const diff = v - Math.min(r, g, b); + const diffc = function(c) { + return (v - c) / 6 / diff + 1 / 2; + }; + if (diff === 0) { + h = 0; + s = 0; + } else { + s = diff / v; + rdif = diffc(r); + gdif = diffc(g); + bdif = diffc(b); + switch (v) { + case r: { + h = bdif - gdif; + break; + } + case g: { + h = 1 / 3 + rdif - bdif; + break; + } + case b: { + h = 2 / 3 + gdif - rdif; + break; + } + } + if (h < 0) { + h += 1; + } else if (h > 1) { + h -= 1; + } + } + return [ + h * 360, + s * 100, + v * 100 + ]; +}; +convert.rgb.hwb = function(rgb) { + const r = rgb[0]; + const g = rgb[1]; + let b = rgb[2]; + const h = convert.rgb.hsl(rgb)[0]; + const w = 1 / 255 * Math.min(r, Math.min(g, b)); + b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); + return [h, w * 100, b * 100]; +}; +convert.rgb.oklab = function(rgb) { + const r = srgbNonlinearTransformInv(rgb[0] / 255); + const g = srgbNonlinearTransformInv(rgb[1] / 255); + const b = srgbNonlinearTransformInv(rgb[2] / 255); + const lp = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b); + const mp = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b); + const sp = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b); + const l = 0.2104542553 * lp + 0.793617785 * mp - 0.0040720468 * sp; + const aa = 1.9779984951 * lp - 2.428592205 * mp + 0.4505937099 * sp; + const bb = 0.0259040371 * lp + 0.7827717662 * mp - 0.808675766 * sp; + return [l * 100, aa * 100, bb * 100]; +}; +convert.rgb.cmyk = function(rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const k = Math.min(1 - r, 1 - g, 1 - b); + const c = (1 - r - k) / (1 - k) || 0; + const m = (1 - g - k) / (1 - k) || 0; + const y = (1 - b - k) / (1 - k) || 0; + return [c * 100, m * 100, y * 100, k * 100]; +}; +function comparativeDistance(x, y) { + return (x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2 + (x[2] - y[2]) ** 2; +} +convert.rgb.keyword = function(rgb) { + const reversed = reverseKeywords[rgb]; + if (reversed) { + return reversed; + } + let currentClosestDistance = Number.POSITIVE_INFINITY; + let currentClosestKeyword; + for (const keyword of Object.keys(color_name_default)) { + const value = color_name_default[keyword]; + const distance = comparativeDistance(rgb, value); + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; + } + } + return currentClosestKeyword; +}; +convert.keyword.rgb = function(keyword) { + return [...color_name_default[keyword]]; +}; +convert.rgb.xyz = function(rgb) { + const r = srgbNonlinearTransformInv(rgb[0] / 255); + const g = srgbNonlinearTransformInv(rgb[1] / 255); + const b = srgbNonlinearTransformInv(rgb[2] / 255); + const x = r * 0.4124564 + g * 0.3575761 + b * 0.1804375; + const y = r * 0.2126729 + g * 0.7151522 + b * 0.072175; + const z = r * 0.0193339 + g * 0.119192 + b * 0.9503041; + return [x * 100, y * 100, z * 100]; +}; +convert.rgb.lab = function(rgb) { + const xyz = convert.rgb.xyz(rgb); + let x = xyz[0]; + let y = xyz[1]; + let z = xyz[2]; + x /= 95.047; + y /= 100; + z /= 108.883; + x = x > LAB_FT ? x ** (1 / 3) : 7.787 * x + 16 / 116; + y = y > LAB_FT ? y ** (1 / 3) : 7.787 * y + 16 / 116; + z = z > LAB_FT ? z ** (1 / 3) : 7.787 * z + 16 / 116; + const l = 116 * y - 16; + const a = 500 * (x - y); + const b = 200 * (y - z); + return [l, a, b]; +}; +convert.hsl.rgb = function(hsl) { + const h = hsl[0] / 360; + const s = hsl[1] / 100; + const l = hsl[2] / 100; + let t3; + let value; + if (s === 0) { + value = l * 255; + return [value, value, value]; + } + const t2 = l < 0.5 ? l * (1 + s) : l + s - l * s; + const t1 = 2 * l - t2; + const rgb = [0, 0, 0]; + for (let i = 0; i < 3; i++) { + t3 = h + 1 / 3 * -(i - 1); + if (t3 < 0) { + t3++; + } + if (t3 > 1) { + t3--; + } + if (6 * t3 < 1) { + value = t1 + (t2 - t1) * 6 * t3; + } else if (2 * t3 < 1) { + value = t2; + } else if (3 * t3 < 2) { + value = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + } else { + value = t1; + } + rgb[i] = value * 255; + } + return rgb; +}; +convert.hsl.hsv = function(hsl) { + const h = hsl[0]; + let s = hsl[1] / 100; + let l = hsl[2] / 100; + let smin = s; + const lmin = Math.max(l, 0.01); + l *= 2; + s *= l <= 1 ? l : 2 - l; + smin *= lmin <= 1 ? lmin : 2 - lmin; + const v = (l + s) / 2; + const sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s); + return [h, sv * 100, v * 100]; +}; +convert.hsv.rgb = function(hsv) { + const h = hsv[0] / 60; + const s = hsv[1] / 100; + let v = hsv[2] / 100; + const hi = Math.floor(h) % 6; + const f = h - Math.floor(h); + const p = 255 * v * (1 - s); + const q = 255 * v * (1 - s * f); + const t = 255 * v * (1 - s * (1 - f)); + v *= 255; + switch (hi) { + case 0: { + return [v, t, p]; + } + case 1: { + return [q, v, p]; + } + case 2: { + return [p, v, t]; + } + case 3: { + return [p, q, v]; + } + case 4: { + return [t, p, v]; + } + case 5: { + return [v, p, q]; + } + } +}; +convert.hsv.hsl = function(hsv) { + const h = hsv[0]; + const s = hsv[1] / 100; + const v = hsv[2] / 100; + const vmin = Math.max(v, 0.01); + let sl; + let l; + l = (2 - s) * v; + const lmin = (2 - s) * vmin; + sl = s * vmin; + sl /= lmin <= 1 ? lmin : 2 - lmin; + sl = sl || 0; + l /= 2; + return [h, sl * 100, l * 100]; +}; +convert.hwb.rgb = function(hwb) { + const h = hwb[0] / 360; + let wh = hwb[1] / 100; + let bl = hwb[2] / 100; + const ratio = wh + bl; + let f; + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } + const i = Math.floor(6 * h); + const v = 1 - bl; + f = 6 * h - i; + if ((i & 1) !== 0) { + f = 1 - f; + } + const n = wh + f * (v - wh); + let r; + let g; + let b; + switch (i) { + default: + case 6: + case 0: { + r = v; + g = n; + b = wh; + break; + } + case 1: { + r = n; + g = v; + b = wh; + break; + } + case 2: { + r = wh; + g = v; + b = n; + break; + } + case 3: { + r = wh; + g = n; + b = v; + break; + } + case 4: { + r = n; + g = wh; + b = v; + break; + } + case 5: { + r = v; + g = wh; + b = n; + break; + } + } + return [r * 255, g * 255, b * 255]; +}; +convert.cmyk.rgb = function(cmyk) { + const c = cmyk[0] / 100; + const m = cmyk[1] / 100; + const y = cmyk[2] / 100; + const k = cmyk[3] / 100; + const r = 1 - Math.min(1, c * (1 - k) + k); + const g = 1 - Math.min(1, m * (1 - k) + k); + const b = 1 - Math.min(1, y * (1 - k) + k); + return [r * 255, g * 255, b * 255]; +}; +convert.xyz.rgb = function(xyz) { + const x = xyz[0] / 100; + const y = xyz[1] / 100; + const z = xyz[2] / 100; + let r; + let g; + let b; + r = x * 3.2404542 + y * -1.5371385 + z * -0.4985314; + g = x * -0.969266 + y * 1.8760108 + z * 0.041556; + b = x * 0.0556434 + y * -0.2040259 + z * 1.0572252; + r = srgbNonlinearTransform(r); + g = srgbNonlinearTransform(g); + b = srgbNonlinearTransform(b); + return [r * 255, g * 255, b * 255]; +}; +convert.xyz.lab = function(xyz) { + let x = xyz[0]; + let y = xyz[1]; + let z = xyz[2]; + x /= 95.047; + y /= 100; + z /= 108.883; + x = x > LAB_FT ? x ** (1 / 3) : 7.787 * x + 16 / 116; + y = y > LAB_FT ? y ** (1 / 3) : 7.787 * y + 16 / 116; + z = z > LAB_FT ? z ** (1 / 3) : 7.787 * z + 16 / 116; + const l = 116 * y - 16; + const a = 500 * (x - y); + const b = 200 * (y - z); + return [l, a, b]; +}; +convert.xyz.oklab = function(xyz) { + const x = xyz[0] / 100; + const y = xyz[1] / 100; + const z = xyz[2] / 100; + const lp = Math.cbrt(0.8189330101 * x + 0.3618667424 * y - 0.1288597137 * z); + const mp = Math.cbrt(0.0329845436 * x + 0.9293118715 * y + 0.0361456387 * z); + const sp = Math.cbrt(0.0482003018 * x + 0.2643662691 * y + 0.633851707 * z); + const l = 0.2104542553 * lp + 0.793617785 * mp - 0.0040720468 * sp; + const a = 1.9779984951 * lp - 2.428592205 * mp + 0.4505937099 * sp; + const b = 0.0259040371 * lp + 0.7827717662 * mp - 0.808675766 * sp; + return [l * 100, a * 100, b * 100]; +}; +convert.oklab.oklch = function(oklab) { + return convert.lab.lch(oklab); +}; +convert.oklab.xyz = function(oklab) { + const ll = oklab[0] / 100; + const a = oklab[1] / 100; + const b = oklab[2] / 100; + const l = (0.999999998 * ll + 0.396337792 * a + 0.215803758 * b) ** 3; + const m = (1.000000008 * ll - 0.105561342 * a - 0.063854175 * b) ** 3; + const s = (1.000000055 * ll - 0.089484182 * a - 1.291485538 * b) ** 3; + const x = 1.227013851 * l - 0.55779998 * m + 0.281256149 * s; + const y = -0.040580178 * l + 1.11225687 * m - 0.071676679 * s; + const z = -0.076381285 * l - 0.421481978 * m + 1.58616322 * s; + return [x * 100, y * 100, z * 100]; +}; +convert.oklab.rgb = function(oklab) { + const ll = oklab[0] / 100; + const aa = oklab[1] / 100; + const bb = oklab[2] / 100; + const l = (ll + 0.3963377774 * aa + 0.2158037573 * bb) ** 3; + const m = (ll - 0.1055613458 * aa - 0.0638541728 * bb) ** 3; + const s = (ll - 0.0894841775 * aa - 1.291485548 * bb) ** 3; + const r = srgbNonlinearTransform(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s); + const g = srgbNonlinearTransform(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s); + const b = srgbNonlinearTransform(-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s); + return [r * 255, g * 255, b * 255]; +}; +convert.oklch.oklab = function(oklch) { + return convert.lch.lab(oklch); +}; +convert.lab.xyz = function(lab) { + const l = lab[0]; + const a = lab[1]; + const b = lab[2]; + let x; + let y; + let z; + y = (l + 16) / 116; + x = a / 500 + y; + z = y - b / 200; + const y2 = y ** 3; + const x2 = x ** 3; + const z2 = z ** 3; + y = y2 > LAB_FT ? y2 : (y - 16 / 116) / 7.787; + x = x2 > LAB_FT ? x2 : (x - 16 / 116) / 7.787; + z = z2 > LAB_FT ? z2 : (z - 16 / 116) / 7.787; + x *= 95.047; + y *= 100; + z *= 108.883; + return [x, y, z]; +}; +convert.lab.lch = function(lab) { + const l = lab[0]; + const a = lab[1]; + const b = lab[2]; + let h; + const hr = Math.atan2(b, a); + h = hr * 360 / 2 / Math.PI; + if (h < 0) { + h += 360; + } + const c = Math.sqrt(a * a + b * b); + return [l, c, h]; +}; +convert.lch.lab = function(lch) { + const l = lch[0]; + const c = lch[1]; + const h = lch[2]; + const hr = h / 360 * 2 * Math.PI; + const a = c * Math.cos(hr); + const b = c * Math.sin(hr); + return [l, a, b]; +}; +convert.rgb.ansi16 = function(args, saturation = null) { + const [r, g, b] = args; + let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; + value = Math.round(value / 50); + if (value === 0) { + return 30; + } + let ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255)); + if (value === 2) { + ansi += 60; + } + return ansi; +}; +convert.hsv.ansi16 = function(args) { + return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); +}; +convert.rgb.ansi256 = function(args) { + const r = args[0]; + const g = args[1]; + const b = args[2]; + if (r >> 4 === g >> 4 && g >> 4 === b >> 4) { + if (r < 8) { + return 16; + } + if (r > 248) { + return 231; + } + return Math.round((r - 8) / 247 * 24) + 232; + } + const ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5); + return ansi; +}; +convert.ansi16.rgb = function(args) { + args = args[0]; + let color = args % 10; + if (color === 0 || color === 7) { + if (args > 50) { + color += 3.5; + } + color = color / 10.5 * 255; + return [color, color, color]; + } + const mult = (Math.trunc(args > 50) + 1) * 0.5; + const r = (color & 1) * mult * 255; + const g = (color >> 1 & 1) * mult * 255; + const b = (color >> 2 & 1) * mult * 255; + return [r, g, b]; +}; +convert.ansi256.rgb = function(args) { + args = args[0]; + if (args >= 232) { + const c = (args - 232) * 10 + 8; + return [c, c, c]; + } + args -= 16; + let rem; + const r = Math.floor(args / 36) / 5 * 255; + const g = Math.floor((rem = args % 36) / 6) / 5 * 255; + const b = rem % 6 / 5 * 255; + return [r, g, b]; +}; +convert.rgb.hex = function(args) { + const integer = ((Math.round(args[0]) & 255) << 16) + ((Math.round(args[1]) & 255) << 8) + (Math.round(args[2]) & 255); + const string = integer.toString(16).toUpperCase(); + return "000000".slice(string.length) + string; +}; +convert.hex.rgb = function(args) { + const match = args.toString(16).match(/[a-f\d]{6}|[a-f\d]{3}/i); + if (!match) { + return [0, 0, 0]; + } + let colorString = match[0]; + if (match[0].length === 3) { + colorString = [...colorString].map((char) => char + char).join(""); + } + const integer = Number.parseInt(colorString, 16); + const r = integer >> 16 & 255; + const g = integer >> 8 & 255; + const b = integer & 255; + return [r, g, b]; +}; +convert.rgb.hcg = function(rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const max = Math.max(Math.max(r, g), b); + const min = Math.min(Math.min(r, g), b); + const chroma = max - min; + let hue; + const grayscale = chroma < 1 ? min / (1 - chroma) : 0; + if (chroma <= 0) { + hue = 0; + } else if (max === r) { + hue = (g - b) / chroma % 6; + } else if (max === g) { + hue = 2 + (b - r) / chroma; + } else { + hue = 4 + (r - g) / chroma; + } + hue /= 6; + hue %= 1; + return [hue * 360, chroma * 100, grayscale * 100]; +}; +convert.hsl.hcg = function(hsl) { + const s = hsl[1] / 100; + const l = hsl[2] / 100; + const c = l < 0.5 ? 2 * s * l : 2 * s * (1 - l); + let f = 0; + if (c < 1) { + f = (l - 0.5 * c) / (1 - c); + } + return [hsl[0], c * 100, f * 100]; +}; +convert.hsv.hcg = function(hsv) { + const s = hsv[1] / 100; + const v = hsv[2] / 100; + const c = s * v; + let f = 0; + if (c < 1) { + f = (v - c) / (1 - c); + } + return [hsv[0], c * 100, f * 100]; +}; +convert.hcg.rgb = function(hcg) { + const h = hcg[0] / 360; + const c = hcg[1] / 100; + const g = hcg[2] / 100; + if (c === 0) { + return [g * 255, g * 255, g * 255]; + } + const pure = [0, 0, 0]; + const hi = h % 1 * 6; + const v = hi % 1; + const w = 1 - v; + let mg = 0; + switch (Math.floor(hi)) { + case 0: { + pure[0] = 1; + pure[1] = v; + pure[2] = 0; + break; + } + case 1: { + pure[0] = w; + pure[1] = 1; + pure[2] = 0; + break; + } + case 2: { + pure[0] = 0; + pure[1] = 1; + pure[2] = v; + break; + } + case 3: { + pure[0] = 0; + pure[1] = w; + pure[2] = 1; + break; + } + case 4: { + pure[0] = v; + pure[1] = 0; + pure[2] = 1; + break; + } + default: { + pure[0] = 1; + pure[1] = 0; + pure[2] = w; + } + } + mg = (1 - c) * g; + return [ + (c * pure[0] + mg) * 255, + (c * pure[1] + mg) * 255, + (c * pure[2] + mg) * 255 + ]; +}; +convert.hcg.hsv = function(hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; + const v = c + g * (1 - c); + let f = 0; + if (v > 0) { + f = c / v; + } + return [hcg[0], f * 100, v * 100]; +}; +convert.hcg.hsl = function(hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; + const l = g * (1 - c) + 0.5 * c; + let s = 0; + if (l > 0 && l < 0.5) { + s = c / (2 * l); + } else if (l >= 0.5 && l < 1) { + s = c / (2 * (1 - l)); + } + return [hcg[0], s * 100, l * 100]; +}; +convert.hcg.hwb = function(hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; + const v = c + g * (1 - c); + return [hcg[0], (v - c) * 100, (1 - v) * 100]; +}; +convert.hwb.hcg = function(hwb) { + const w = hwb[1] / 100; + const b = hwb[2] / 100; + const v = 1 - b; + const c = v - w; + let g = 0; + if (c < 1) { + g = (v - c) / (1 - c); + } + return [hwb[0], c * 100, g * 100]; +}; +convert.apple.rgb = function(apple) { + return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255]; +}; +convert.rgb.apple = function(rgb) { + return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535]; +}; +convert.gray.rgb = function(args) { + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; +}; +convert.gray.hsl = function(args) { + return [0, 0, args[0]]; +}; +convert.gray.hsv = convert.gray.hsl; +convert.gray.hwb = function(gray) { + return [0, 100, gray[0]]; +}; +convert.gray.cmyk = function(gray) { + return [0, 0, 0, gray[0]]; +}; +convert.gray.lab = function(gray) { + return [gray[0], 0, 0]; +}; +convert.gray.hex = function(gray) { + const value = Math.round(gray[0] / 100 * 255) & 255; + const integer = (value << 16) + (value << 8) + value; + const string = integer.toString(16).toUpperCase(); + return "000000".slice(string.length) + string; +}; +convert.rgb.gray = function(rgb) { + const value = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [value / 255 * 100]; +}; + +// node_modules/color-convert/route.js +function buildGraph() { + const graph = {}; + const models2 = Object.keys(conversions_default); + for (let { length } = models2, i = 0; i < length; i++) { + graph[models2[i]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } + return graph; +} +function deriveBFS(fromModel) { + const graph = buildGraph(); + const queue = [fromModel]; + graph[fromModel].distance = 0; + while (queue.length > 0) { + const current = queue.pop(); + const adjacents = Object.keys(conversions_default[current]); + for (let { length } = adjacents, i = 0; i < length; i++) { + const adjacent = adjacents[i]; + const node = graph[adjacent]; + if (node.distance === -1) { + node.distance = graph[current].distance + 1; + node.parent = current; + queue.unshift(adjacent); + } + } + } + return graph; +} +function link(from, to) { + return function(args) { + return to(from(args)); + }; +} +function wrapConversion(toModel, graph) { + const path = [graph[toModel].parent, toModel]; + let fn = conversions_default[graph[toModel].parent][toModel]; + let cur = graph[toModel].parent; + while (graph[cur].parent) { + path.unshift(graph[cur].parent); + fn = link(conversions_default[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } + fn.conversion = path; + return fn; +} +function route(fromModel) { + const graph = deriveBFS(fromModel); + const conversion = {}; + const models2 = Object.keys(graph); + for (let { length } = models2, i = 0; i < length; i++) { + const toModel = models2[i]; + const node = graph[toModel]; + if (node.parent === null) { + continue; + } + conversion[toModel] = wrapConversion(toModel, graph); + } + return conversion; +} +var route_default = route; + +// node_modules/color-convert/index.js +var convert2 = {}; +var models = Object.keys(conversions_default); +function wrapRaw(fn) { + const wrappedFn = function(...args) { + const arg0 = args[0]; + if (arg0 === void 0 || arg0 === null) { + return arg0; + } + if (arg0.length > 1) { + args = arg0; + } + return fn(args); + }; + if ("conversion" in fn) { + wrappedFn.conversion = fn.conversion; + } + return wrappedFn; +} +function wrapRounded(fn) { + const wrappedFn = function(...args) { + const arg0 = args[0]; + if (arg0 === void 0 || arg0 === null) { + return arg0; + } + if (arg0.length > 1) { + args = arg0; + } + const result = fn(args); + if (typeof result === "object") { + for (let { length } = result, i = 0; i < length; i++) { + result[i] = Math.round(result[i]); + } + } + return result; + }; + if ("conversion" in fn) { + wrappedFn.conversion = fn.conversion; + } + return wrappedFn; +} +for (const fromModel of models) { + convert2[fromModel] = {}; + Object.defineProperty(convert2[fromModel], "channels", { value: conversions_default[fromModel].channels }); + Object.defineProperty(convert2[fromModel], "labels", { value: conversions_default[fromModel].labels }); + const routes = route_default(fromModel); + const routeModels = Object.keys(routes); + for (const toModel of routeModels) { + const fn = routes[toModel]; + convert2[fromModel][toModel] = wrapRounded(fn); + convert2[fromModel][toModel].raw = wrapRaw(fn); + } +} +var color_convert_default = convert2; + +// node_modules/color/index.js +var skippedModels = [ + // To be honest, I don't really feel like keyword belongs in color convert, but eh. + "keyword", + // Gray conflicts with some method names, and has its own method defined. + "gray", + // Shouldn't really be in color-convert either... + "hex" +]; +var hashedModelKeys = {}; +for (const model of Object.keys(color_convert_default)) { + hashedModelKeys[[...color_convert_default[model].labels].sort().join("")] = model; +} +var limiters = {}; +function Color(object, model) { + if (!(this instanceof Color)) { + return new Color(object, model); + } + if (model && model in skippedModels) { + model = null; + } + if (model && !(model in color_convert_default)) { + throw new Error("Unknown model: " + model); + } + let i; + let channels; + if (object == null) { + this.model = "rgb"; + this.color = [0, 0, 0]; + this.valpha = 1; + } else if (object instanceof Color) { + this.model = object.model; + this.color = [...object.color]; + this.valpha = object.valpha; + } else if (typeof object === "string") { + const result = color_string_default.get(object); + if (result === null) { + throw new Error("Unable to parse color from string: " + object); + } + this.model = result.model; + channels = color_convert_default[this.model].channels; + this.color = result.value.slice(0, channels); + this.valpha = typeof result.value[channels] === "number" ? result.value[channels] : 1; + } else if (object.length > 0) { + this.model = model || "rgb"; + channels = color_convert_default[this.model].channels; + const newArray = Array.prototype.slice.call(object, 0, channels); + this.color = zeroArray(newArray, channels); + this.valpha = typeof object[channels] === "number" ? object[channels] : 1; + } else if (typeof object === "number") { + this.model = "rgb"; + this.color = [ + object >> 16 & 255, + object >> 8 & 255, + object & 255 + ]; + this.valpha = 1; + } else { + this.valpha = 1; + const keys = Object.keys(object); + if ("alpha" in object) { + keys.splice(keys.indexOf("alpha"), 1); + this.valpha = typeof object.alpha === "number" ? object.alpha : 0; + } + const hashedKeys = keys.sort().join(""); + if (!(hashedKeys in hashedModelKeys)) { + throw new Error("Unable to parse color from object: " + JSON.stringify(object)); + } + this.model = hashedModelKeys[hashedKeys]; + const { labels } = color_convert_default[this.model]; + const color = []; + for (i = 0; i < labels.length; i++) { + color.push(object[labels[i]]); + } + this.color = zeroArray(color); + } + if (limiters[this.model]) { + channels = color_convert_default[this.model].channels; + for (i = 0; i < channels; i++) { + const limit = limiters[this.model][i]; + if (limit) { + this.color[i] = limit(this.color[i]); + } + } + } + this.valpha = Math.max(0, Math.min(1, this.valpha)); + if (Object.freeze) { + Object.freeze(this); + } +} +Color.prototype = { + toString() { + return this.string(); + }, + toJSON() { + return this[this.model](); + }, + string(places) { + let self = this.model in color_string_default.to ? this : this.rgb(); + self = self.round(typeof places === "number" ? places : 1); + const arguments_ = self.valpha === 1 ? self.color : [...self.color, this.valpha]; + return color_string_default.to[self.model](...arguments_); + }, + percentString(places) { + const self = this.rgb().round(typeof places === "number" ? places : 1); + const arguments_ = self.valpha === 1 ? self.color : [...self.color, this.valpha]; + return color_string_default.to.rgb.percent(...arguments_); + }, + array() { + return this.valpha === 1 ? [...this.color] : [...this.color, this.valpha]; + }, + object() { + const result = {}; + const { channels } = color_convert_default[this.model]; + const { labels } = color_convert_default[this.model]; + for (let i = 0; i < channels; i++) { + result[labels[i]] = this.color[i]; + } + if (this.valpha !== 1) { + result.alpha = this.valpha; + } + return result; + }, + unitArray() { + const rgb = this.rgb().color; + rgb[0] /= 255; + rgb[1] /= 255; + rgb[2] /= 255; + if (this.valpha !== 1) { + rgb.push(this.valpha); + } + return rgb; + }, + unitObject() { + const rgb = this.rgb().object(); + rgb.r /= 255; + rgb.g /= 255; + rgb.b /= 255; + if (this.valpha !== 1) { + rgb.alpha = this.valpha; + } + return rgb; + }, + round(places) { + places = Math.max(places || 0, 0); + return new Color([...this.color.map(roundToPlace(places)), this.valpha], this.model); + }, + alpha(value) { + if (value !== void 0) { + return new Color([...this.color, Math.max(0, Math.min(1, value))], this.model); + } + return this.valpha; + }, + // Rgb + red: getset("rgb", 0, maxfn(255)), + green: getset("rgb", 1, maxfn(255)), + blue: getset("rgb", 2, maxfn(255)), + hue: getset(["hsl", "hsv", "hsl", "hwb", "hcg"], 0, (value) => (value % 360 + 360) % 360), + saturationl: getset("hsl", 1, maxfn(100)), + lightness: getset("hsl", 2, maxfn(100)), + saturationv: getset("hsv", 1, maxfn(100)), + value: getset("hsv", 2, maxfn(100)), + chroma: getset("hcg", 1, maxfn(100)), + gray: getset("hcg", 2, maxfn(100)), + white: getset("hwb", 1, maxfn(100)), + wblack: getset("hwb", 2, maxfn(100)), + cyan: getset("cmyk", 0, maxfn(100)), + magenta: getset("cmyk", 1, maxfn(100)), + yellow: getset("cmyk", 2, maxfn(100)), + black: getset("cmyk", 3, maxfn(100)), + x: getset("xyz", 0, maxfn(95.047)), + y: getset("xyz", 1, maxfn(100)), + z: getset("xyz", 2, maxfn(108.833)), + l: getset("lab", 0, maxfn(100)), + a: getset("lab", 1), + b: getset("lab", 2), + keyword(value) { + if (value !== void 0) { + return new Color(value); + } + return color_convert_default[this.model].keyword(this.color); + }, + hex(value) { + if (value !== void 0) { + return new Color(value); + } + return color_string_default.to.hex(...this.rgb().round().color); + }, + hexa(value) { + if (value !== void 0) { + return new Color(value); + } + const rgbArray = this.rgb().round().color; + let alphaHex = Math.round(this.valpha * 255).toString(16).toUpperCase(); + if (alphaHex.length === 1) { + alphaHex = "0" + alphaHex; + } + return color_string_default.to.hex(...rgbArray) + alphaHex; + }, + rgbNumber() { + const rgb = this.rgb().color; + return (rgb[0] & 255) << 16 | (rgb[1] & 255) << 8 | rgb[2] & 255; + }, + luminosity() { + const rgb = this.rgb().color; + const lum = []; + for (const [i, element] of rgb.entries()) { + const chan = element / 255; + lum[i] = chan <= 0.04045 ? chan / 12.92 : ((chan + 0.055) / 1.055) ** 2.4; + } + return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2]; + }, + contrast(color2) { + const lum1 = this.luminosity(); + const lum2 = color2.luminosity(); + if (lum1 > lum2) { + return (lum1 + 0.05) / (lum2 + 0.05); + } + return (lum2 + 0.05) / (lum1 + 0.05); + }, + level(color2) { + const contrastRatio = this.contrast(color2); + if (contrastRatio >= 7) { + return "AAA"; + } + return contrastRatio >= 4.5 ? "AA" : ""; + }, + isDark() { + const rgb = this.rgb().color; + const yiq = (rgb[0] * 2126 + rgb[1] * 7152 + rgb[2] * 722) / 1e4; + return yiq < 128; + }, + isLight() { + return !this.isDark(); + }, + negate() { + const rgb = this.rgb(); + for (let i = 0; i < 3; i++) { + rgb.color[i] = 255 - rgb.color[i]; + } + return rgb; + }, + lighten(ratio) { + const hsl = this.hsl(); + hsl.color[2] += hsl.color[2] * ratio; + return hsl; + }, + darken(ratio) { + const hsl = this.hsl(); + hsl.color[2] -= hsl.color[2] * ratio; + return hsl; + }, + saturate(ratio) { + const hsl = this.hsl(); + hsl.color[1] += hsl.color[1] * ratio; + return hsl; + }, + desaturate(ratio) { + const hsl = this.hsl(); + hsl.color[1] -= hsl.color[1] * ratio; + return hsl; + }, + whiten(ratio) { + const hwb = this.hwb(); + hwb.color[1] += hwb.color[1] * ratio; + return hwb; + }, + blacken(ratio) { + const hwb = this.hwb(); + hwb.color[2] += hwb.color[2] * ratio; + return hwb; + }, + grayscale() { + const rgb = this.rgb().color; + const value = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11; + return Color.rgb(value, value, value); + }, + fade(ratio) { + return this.alpha(this.valpha - this.valpha * ratio); + }, + opaquer(ratio) { + return this.alpha(this.valpha + this.valpha * ratio); + }, + rotate(degrees) { + const hsl = this.hsl(); + let hue = hsl.color[0]; + hue = (hue + degrees) % 360; + hue = hue < 0 ? 360 + hue : hue; + hsl.color[0] = hue; + return hsl; + }, + mix(mixinColor, weight) { + if (!mixinColor || !mixinColor.rgb) { + throw new Error('Argument to "mix" was not a Color instance, but rather an instance of ' + typeof mixinColor); + } + const color1 = mixinColor.rgb(); + const color2 = this.rgb(); + const p = weight === void 0 ? 0.5 : weight; + const w = 2 * p - 1; + const a = color1.alpha() - color2.alpha(); + const w1 = ((w * a === -1 ? w : (w + a) / (1 + w * a)) + 1) / 2; + const w2 = 1 - w1; + return Color.rgb( + w1 * color1.red() + w2 * color2.red(), + w1 * color1.green() + w2 * color2.green(), + w1 * color1.blue() + w2 * color2.blue(), + color1.alpha() * p + color2.alpha() * (1 - p) + ); + } +}; +for (const model of Object.keys(color_convert_default)) { + if (skippedModels.includes(model)) { + continue; + } + const { channels } = color_convert_default[model]; + Color.prototype[model] = function(...arguments_) { + if (this.model === model) { + return new Color(this); + } + if (arguments_.length > 0) { + return new Color(arguments_, model); + } + return new Color([...assertArray(color_convert_default[this.model][model].raw(this.color)), this.valpha], model); + }; + Color[model] = function(...arguments_) { + let color = arguments_[0]; + if (typeof color === "number") { + color = zeroArray(arguments_, channels); + } + return new Color(color, model); + }; +} +function roundTo(number, places) { + return Number(number.toFixed(places)); +} +function roundToPlace(places) { + return function(number) { + return roundTo(number, places); + }; +} +function getset(model, channel, modifier) { + model = Array.isArray(model) ? model : [model]; + for (const m of model) { + (limiters[m] ||= [])[channel] = modifier; + } + model = model[0]; + return function(value) { + let result; + if (value !== void 0) { + if (modifier) { + value = modifier(value); + } + result = this[model](); + result.color[channel] = value; + return result; + } + result = this[model]().color[channel]; + if (modifier) { + result = modifier(result); + } + return result; + }; +} +function maxfn(max) { + return function(v) { + return Math.max(0, Math.min(max, v)); + }; +} +function assertArray(value) { + return Array.isArray(value) ? value : [value]; +} +function zeroArray(array, length) { + for (let i = 0; i < length; i++) { + if (typeof array[i] !== "number") { + array[i] = 0; + } + } + return array; +} +var index_default = Color; diff --git a/node_modules/@img/colour/index.cjs b/node_modules/@img/colour/index.cjs new file mode 100644 index 0000000..25596b2 --- /dev/null +++ b/node_modules/@img/colour/index.cjs @@ -0,0 +1 @@ +module.exports = require("./color.cjs").default; diff --git a/node_modules/@img/colour/index.d.ts b/node_modules/@img/colour/index.d.ts new file mode 100644 index 0000000..ca2461f --- /dev/null +++ b/node_modules/@img/colour/index.d.ts @@ -0,0 +1,929 @@ +// Generated by dts-bundle-generator v9.5.1 + +type Channels = number; +type RGB = [ + r: number, + g: number, + b: number +]; +type HSL = [ + h: number, + s: number, + l: number +]; +type HSV = [ + h: number, + s: number, + v: number +]; +type CMYK = [ + c: number, + m: number, + y: number, + k: number +]; +type LAB = [ + l: number, + a: number, + b: number +]; +type LCH = [ + l: number, + c: number, + h: number +]; +type HCG = [ + h: number, + c: number, + g: number +]; +type HWB = [ + h: number, + w: number, + b: number +]; +type XYZ = [ + x: number, + y: number, + z: number +]; +type Apple = [ + r16: number, + g16: number, + b16: number +]; +type Gray = [ + gray: number +]; +type ANSI16 = number; +type ANSI256 = number; +type Keyword = string; +type HEX = string; +declare namespace route { + type rgb = { + hsl(from: RGB): HSL; + hsl(...from: RGB): HSL; + hsl(from: RGB): HSL; + hsl(...from: RGB): HSL; + hsv(from: RGB): HSV; + hsv(...from: RGB): HSV; + hwb(from: RGB): HWB; + hwb(...from: RGB): HWB; + cmyk(from: RGB): CMYK; + cmyk(...from: RGB): CMYK; + xyz(from: RGB): XYZ; + xyz(...from: RGB): XYZ; + lab(from: RGB): LAB; + lab(...from: RGB): LAB; + lch(from: RGB): LCH; + lch(...from: RGB): LCH; + hex(from: RGB): HEX; + hex(...from: RGB): HEX; + keyword(from: RGB): Keyword; + keyword(...from: RGB): Keyword; + ansi16(from: RGB): ANSI16; + ansi16(...from: RGB): ANSI16; + ansi256(from: RGB): ANSI256; + ansi256(...from: RGB): ANSI256; + hcg(from: RGB): HCG; + hcg(...from: RGB): HCG; + apple(from: RGB): Apple; + apple(...from: RGB): Apple; + gray(from: RGB): Gray; + gray(...from: RGB): Gray; + }; + type hsl = { + rgb(from: HSL): RGB; + rgb(...from: HSL): RGB; + hsv(from: HSL): HSV; + hsv(...from: HSL): HSV; + hwb(from: HSL): HWB; + hwb(...from: HSL): HWB; + cmyk(from: HSL): CMYK; + cmyk(...from: HSL): CMYK; + xyz(from: HSL): XYZ; + xyz(...from: HSL): XYZ; + lab(from: HSL): LAB; + lab(...from: HSL): LAB; + lch(from: HSL): LCH; + lch(...from: HSL): LCH; + hex(from: HSL): HEX; + hex(...from: HSL): HEX; + keyword(from: HSL): Keyword; + keyword(...from: HSL): Keyword; + ansi16(from: HSL): ANSI16; + ansi16(...from: HSL): ANSI16; + ansi256(from: HSL): ANSI256; + ansi256(...from: HSL): ANSI256; + hcg(from: HSL): HCG; + hcg(...from: HSL): HCG; + apple(from: HSL): Apple; + apple(...from: HSL): Apple; + gray(from: HSL): Gray; + gray(...from: HSL): Gray; + }; + type hsv = { + rgb(from: HSV): RGB; + rgb(...from: HSV): RGB; + hsl(from: HSV): HSL; + hsl(...from: HSV): HSL; + hwb(from: HSV): HWB; + hwb(...from: HSV): HWB; + cmyk(from: HSV): CMYK; + cmyk(...from: HSV): CMYK; + xyz(from: HSV): XYZ; + xyz(...from: HSV): XYZ; + lab(from: HSV): LAB; + lab(...from: HSV): LAB; + lch(from: HSV): LCH; + lch(...from: HSV): LCH; + hex(from: HSV): HEX; + hex(...from: HSV): HEX; + keyword(from: HSV): Keyword; + keyword(...from: HSV): Keyword; + ansi16(from: HSV): ANSI16; + ansi16(...from: HSV): ANSI16; + ansi256(from: HSV): ANSI256; + ansi256(...from: HSV): ANSI256; + hcg(from: HSV): HCG; + hcg(...from: HSV): HCG; + apple(from: HSV): Apple; + apple(...from: HSV): Apple; + gray(from: HSV): Gray; + gray(...from: HSV): Gray; + }; + type hwb = { + rgb(from: HWB): RGB; + rgb(...from: HWB): RGB; + hsl(from: HWB): HSL; + hsl(...from: HWB): HSL; + hsv(from: HWB): HSV; + hsv(...from: HWB): HSV; + cmyk(from: HWB): CMYK; + cmyk(...from: HWB): CMYK; + xyz(from: HWB): XYZ; + xyz(...from: HWB): XYZ; + lab(from: HWB): LAB; + lab(...from: HWB): LAB; + lch(from: HWB): LCH; + lch(...from: HWB): LCH; + hex(from: HWB): HEX; + hex(...from: HWB): HEX; + keyword(from: HWB): Keyword; + keyword(...from: HWB): Keyword; + ansi16(from: HWB): ANSI16; + ansi16(...from: HWB): ANSI16; + ansi256(from: HWB): ANSI256; + ansi256(...from: HWB): ANSI256; + hcg(from: HWB): HCG; + hcg(...from: HWB): HCG; + apple(from: HWB): Apple; + apple(...from: HWB): Apple; + gray(from: HWB): Gray; + gray(...from: HWB): Gray; + }; + type cmyk = { + rgb(from: CMYK): RGB; + rgb(...from: CMYK): RGB; + hsl(from: CMYK): HSL; + hsl(...from: CMYK): HSL; + hsv(from: CMYK): HSV; + hsv(...from: CMYK): HSV; + hwb(from: CMYK): HWB; + hwb(...from: CMYK): HWB; + xyz(from: CMYK): XYZ; + xyz(...from: CMYK): XYZ; + lab(from: CMYK): LAB; + lab(...from: CMYK): LAB; + lch(from: CMYK): LCH; + lch(...from: CMYK): LCH; + hex(from: CMYK): HEX; + hex(...from: CMYK): HEX; + keyword(from: CMYK): Keyword; + keyword(...from: CMYK): Keyword; + ansi16(from: CMYK): ANSI16; + ansi16(...from: CMYK): ANSI16; + ansi256(from: CMYK): ANSI256; + ansi256(...from: CMYK): ANSI256; + hcg(from: CMYK): HCG; + hcg(...from: CMYK): HCG; + apple(from: CMYK): Apple; + apple(...from: CMYK): Apple; + gray(from: CMYK): Gray; + gray(...from: CMYK): Gray; + }; + type xyz = { + rgb(from: XYZ): RGB; + rgb(...from: XYZ): RGB; + hsl(from: XYZ): HSL; + hsl(...from: XYZ): HSL; + hsv(from: XYZ): HSV; + hsv(...from: XYZ): HSV; + hwb(from: XYZ): HWB; + hwb(...from: XYZ): HWB; + cmyk(from: XYZ): CMYK; + cmyk(...from: XYZ): CMYK; + lab(from: XYZ): LAB; + lab(...from: XYZ): LAB; + lch(from: XYZ): LCH; + lch(...from: XYZ): LCH; + hex(from: XYZ): HEX; + hex(...from: XYZ): HEX; + keyword(from: XYZ): Keyword; + keyword(...from: XYZ): Keyword; + ansi16(from: XYZ): ANSI16; + ansi16(...from: XYZ): ANSI16; + ansi256(from: XYZ): ANSI256; + ansi256(...from: XYZ): ANSI256; + hcg(from: XYZ): HCG; + hcg(...from: XYZ): HCG; + apple(from: XYZ): Apple; + apple(...from: XYZ): Apple; + gray(from: XYZ): Gray; + gray(...from: XYZ): Gray; + }; + type lab = { + rgb(from: LAB): RGB; + rgb(...from: LAB): RGB; + hsl(from: LAB): HSL; + hsl(...from: LAB): HSL; + hsv(from: LAB): HSV; + hsv(...from: LAB): HSV; + hwb(from: LAB): HWB; + hwb(...from: LAB): HWB; + cmyk(from: LAB): CMYK; + cmyk(...from: LAB): CMYK; + xyz(from: LAB): XYZ; + xyz(...from: LAB): XYZ; + lch(from: LAB): LCH; + lch(...from: LAB): LCH; + hex(from: LAB): HEX; + hex(...from: LAB): HEX; + keyword(from: LAB): Keyword; + keyword(...from: LAB): Keyword; + ansi16(from: LAB): ANSI16; + ansi16(...from: LAB): ANSI16; + ansi256(from: LAB): ANSI256; + ansi256(...from: LAB): ANSI256; + hcg(from: LAB): HCG; + hcg(...from: LAB): HCG; + apple(from: LAB): Apple; + apple(...from: LAB): Apple; + gray(from: LAB): Gray; + gray(...from: LAB): Gray; + }; + type lch = { + rgb(from: LCH): RGB; + rgb(...from: LCH): RGB; + hsl(from: LCH): HSL; + hsl(...from: LCH): HSL; + hsv(from: LCH): HSV; + hsv(...from: LCH): HSV; + hwb(from: LCH): HWB; + hwb(...from: LCH): HWB; + cmyk(from: LCH): CMYK; + cmyk(...from: LCH): CMYK; + xyz(from: LCH): XYZ; + xyz(...from: LCH): XYZ; + lab(from: LCH): LAB; + lab(...from: LCH): LAB; + hex(from: LCH): HEX; + hex(...from: LCH): HEX; + keyword(from: LCH): Keyword; + keyword(...from: LCH): Keyword; + ansi16(from: LCH): ANSI16; + ansi16(...from: LCH): ANSI16; + ansi256(from: LCH): ANSI256; + ansi256(...from: LCH): ANSI256; + hcg(from: LCH): HCG; + hcg(...from: LCH): HCG; + apple(from: LCH): Apple; + apple(...from: LCH): Apple; + gray(from: LCH): Gray; + gray(...from: LCH): Gray; + }; + type hex = { + rgb(from: HEX): RGB; + hsl(from: HEX): HSL; + hsv(from: HEX): HSV; + hwb(from: HEX): HWB; + cmyk(from: HEX): CMYK; + xyz(from: HEX): XYZ; + lab(from: HEX): LAB; + lch(from: HEX): LCH; + keyword(from: HEX): Keyword; + ansi16(from: HEX): ANSI16; + ansi256(from: HEX): ANSI256; + hcg(from: HEX): HCG; + apple(from: HEX): Apple; + gray(from: HEX): Gray; + }; + type keyword = { + rgb(from: Keyword): RGB; + hsl(from: Keyword): HSL; + hsv(from: Keyword): HSV; + hwb(from: Keyword): HWB; + cmyk(from: Keyword): CMYK; + xyz(from: Keyword): XYZ; + lab(from: Keyword): LAB; + lch(from: Keyword): LCH; + hex(from: Keyword): HEX; + ansi16(from: Keyword): ANSI16; + ansi256(from: Keyword): ANSI256; + hcg(from: Keyword): HCG; + apple(from: Keyword): Apple; + gray(from: Keyword): Gray; + }; + type ansi16 = { + rgb(from: ANSI16): RGB; + hsl(from: ANSI16): HSL; + hsv(from: ANSI16): HSV; + hwb(from: ANSI16): HWB; + cmyk(from: ANSI16): CMYK; + xyz(from: ANSI16): XYZ; + lab(from: ANSI16): LAB; + lch(from: ANSI16): LCH; + hex(from: ANSI16): HEX; + keyword(from: ANSI16): Keyword; + ansi256(from: ANSI16): ANSI256; + hcg(from: ANSI16): HCG; + apple(from: ANSI16): Apple; + gray(from: ANSI16): Gray; + }; + type ansi256 = { + rgb(from: ANSI256): RGB; + hsl(from: ANSI256): HSL; + hsv(from: ANSI256): HSV; + hwb(from: ANSI256): HWB; + cmyk(from: ANSI256): CMYK; + xyz(from: ANSI256): XYZ; + lab(from: ANSI256): LAB; + lch(from: ANSI256): LCH; + hex(from: ANSI256): HEX; + keyword(from: ANSI256): Keyword; + ansi16(from: ANSI256): ANSI16; + hcg(from: ANSI256): HCG; + apple(from: ANSI256): Apple; + gray(from: ANSI256): Gray; + }; + type hcg = { + rgb(from: HCG): RGB; + rgb(...from: HCG): RGB; + hsl(from: HCG): HSL; + hsl(...from: HCG): HSL; + hsv(from: HCG): HSV; + hsv(...from: HCG): HSV; + hwb(from: HCG): HWB; + hwb(...from: HCG): HWB; + cmyk(from: HCG): CMYK; + cmyk(...from: HCG): CMYK; + xyz(from: HCG): XYZ; + xyz(...from: HCG): XYZ; + lab(from: HCG): LAB; + lab(...from: HCG): LAB; + lch(from: HCG): LCH; + lch(...from: HCG): LCH; + hex(from: HCG): HEX; + hex(...from: HCG): HEX; + keyword(from: HCG): Keyword; + keyword(...from: HCG): Keyword; + ansi16(from: HCG): ANSI16; + ansi16(...from: HCG): ANSI16; + ansi256(from: HCG): ANSI256; + ansi256(...from: HCG): ANSI256; + apple(from: HCG): Apple; + apple(...from: HCG): Apple; + gray(from: HCG): Gray; + gray(...from: HCG): Gray; + }; + type apple = { + rgb(from: Apple): RGB; + rgb(...from: Apple): RGB; + hsl(from: Apple): HSL; + hsl(...from: Apple): HSL; + hsv(from: Apple): HSV; + hsv(...from: Apple): HSV; + hwb(from: Apple): HWB; + hwb(...from: Apple): HWB; + cmyk(from: Apple): CMYK; + cmyk(...from: Apple): CMYK; + xyz(from: Apple): XYZ; + xyz(...from: Apple): XYZ; + lab(from: Apple): LAB; + lab(...from: Apple): LAB; + lch(from: Apple): LCH; + lch(...from: Apple): LCH; + hex(from: Apple): HEX; + hex(...from: Apple): HEX; + keyword(from: Apple): Keyword; + keyword(...from: Apple): Keyword; + ansi16(from: Apple): ANSI16; + ansi16(...from: Apple): ANSI16; + ansi256(from: Apple): ANSI256; + ansi256(...from: Apple): ANSI256; + hcg(from: Apple): HCG; + hcg(...from: Apple): HCG; + gray(from: Apple): Gray; + gray(...from: Apple): Gray; + }; + type gray = { + rgb(from: Gray): RGB; + rgb(...from: Gray): RGB; + hsl(from: Gray): HSL; + hsl(...from: Gray): HSL; + hsv(from: Gray): HSV; + hsv(...from: Gray): HSV; + hwb(from: Gray): HWB; + hwb(...from: Gray): HWB; + cmyk(from: Gray): CMYK; + cmyk(...from: Gray): CMYK; + xyz(from: Gray): XYZ; + xyz(...from: Gray): XYZ; + lab(from: Gray): LAB; + lab(...from: Gray): LAB; + lch(from: Gray): LCH; + lch(...from: Gray): LCH; + hex(from: Gray): HEX; + hex(...from: Gray): HEX; + keyword(from: Gray): Keyword; + keyword(...from: Gray): Keyword; + ansi16(from: Gray): ANSI16; + ansi16(...from: Gray): ANSI16; + ansi256(from: Gray): ANSI256; + ansi256(...from: Gray): ANSI256; + hcg(from: Gray): HCG; + hcg(...from: Gray): HCG; + apple(from: Gray): Apple; + apple(...from: Gray): Apple; + }; +} +declare function route(fromModel: "rgb"): route.rgb; +declare function route(fromModel: "hsl"): route.hsl; +declare function route(fromModel: "hsv"): route.hsv; +declare function route(fromModel: "hwb"): route.hwb; +declare function route(fromModel: "cmyk"): route.cmyk; +declare function route(fromModel: "xyz"): route.xyz; +declare function route(fromModel: "lab"): route.lab; +declare function route(fromModel: "lch"): route.lch; +declare function route(fromModel: "hex"): route.hex; +declare function route(fromModel: "keyword"): route.keyword; +declare function route(fromModel: "ansi16"): route.ansi16; +declare function route(fromModel: "ansi256"): route.ansi256; +declare function route(fromModel: "hcg"): route.hcg; +declare function route(fromModel: "apple"): route.apple; +declare function route(fromModel: "gray"): route.gray; +type Convert = { + rgb: { + channels: Channels; + labels: "rgb"; + hsl: { + (...rgb: RGB): HSL; + raw: (...rgb: RGB) => HSL; + }; + hsv: { + (...rgb: RGB): HSV; + raw: (...rgb: RGB) => HSV; + }; + hwb: { + (...rgb: RGB): HWB; + raw: (...rgb: RGB) => HWB; + }; + hcg: { + (...rgb: RGB): HCG; + raw: (...rgb: RGB) => HCG; + }; + cmyk: { + (...rgb: RGB): CMYK; + raw: (...rgb: RGB) => CMYK; + }; + keyword: { + (...rgb: RGB): Keyword; + raw: (...rgb: RGB) => Keyword; + }; + ansi16: { + (...rgb: RGB): ANSI16; + raw: (...rgb: RGB) => ANSI16; + }; + ansi256: { + (...rgb: RGB): ANSI256; + raw: (...rgb: RGB) => ANSI256; + }; + apple: { + (...rgb: RGB): Apple; + raw: (...rgb: RGB) => Apple; + }; + hex: { + (...rgb: RGB): HEX; + raw: (...rgb: RGB) => HEX; + }; + gray: { + (...rgb: RGB): Gray; + raw: (...rgb: RGB) => Gray; + }; + } & route.rgb & { + [F in keyof route.rgb]: { + raw: route.rgb[F]; + }; + }; + keyword: { + channels: Channels; + rgb: { + (keyword: Keyword): RGB; + raw: (keyword: Keyword) => RGB; + }; + } & route.keyword & { + [F in keyof route.keyword]: { + raw: route.keyword[F]; + }; + }; + hsl: { + channels: Channels; + labels: "hsl"; + rgb: { + (...hsl: HSL): RGB; + raw: (...hsl: HSL) => RGB; + }; + hsv: { + (...hsl: HSL): HSV; + raw: (...hsl: HSL) => HSV; + }; + hcg: { + (...hsl: HSL): HCG; + raw: (...hsl: HSL) => HCG; + }; + } & route.hsl & { + [F in keyof route.hsl]: { + raw: route.hsl[F]; + }; + }; + hsv: { + channels: Channels; + labels: "hsv"; + hcg: { + (...hsv: HSV): HCG; + raw: (...hsv: HSV) => HCG; + }; + rgb: { + (...hsv: HSV): RGB; + raw: (...hsv: HSV) => RGB; + }; + hsv: { + (...hsv: HSV): HSV; + raw: (...hsv: HSV) => HSV; + }; + hsl: { + (...hsv: HSV): HSL; + raw: (...hsv: HSV) => HSL; + }; + hwb: { + (...hsv: HSV): HWB; + raw: (...hsv: HSV) => HWB; + }; + ansi16: { + (...hsv: HSV): ANSI16; + raw: (...hsv: HSV) => ANSI16; + }; + } & route.hsv & { + [F in keyof route.hsv]: { + raw: route.hsv[F]; + }; + }; + hwb: { + channels: Channels; + labels: "hwb"; + hcg: { + (...hwb: HWB): HCG; + raw: (...hwb: HWB) => HCG; + }; + rgb: { + (...hwb: HWB): RGB; + raw: (...hwb: HWB) => RGB; + }; + } & route.hwb & { + [F in keyof route.hwb]: { + raw: route.hwb[F]; + }; + }; + cmyk: { + channels: Channels; + labels: "cmyk"; + rgb: { + (...cmyk: CMYK): RGB; + raw: (...cmyk: CMYK) => RGB; + }; + } & route.cmyk & { + [F in keyof route.cmyk]: { + raw: route.cmyk[F]; + }; + }; + xyz: { + channels: Channels; + labels: "xyz"; + rgb: { + (...xyz: XYZ): RGB; + raw: (...xyz: XYZ) => RGB; + }; + lab: { + (...xyz: XYZ): LAB; + raw: (...xyz: XYZ) => LAB; + }; + } & route.xyz & { + [F in keyof route.xyz]: { + raw: route.xyz[F]; + }; + }; + lab: { + channels: Channels; + labels: "lab"; + xyz: { + (...lab: LAB): XYZ; + raw: (...lab: LAB) => XYZ; + }; + lch: { + (...lab: LAB): LCH; + raw: (...lab: LAB) => LCH; + }; + } & route.lab & { + [F in keyof route.lab]: { + raw: route.lab[F]; + }; + }; + lch: { + channels: Channels; + labels: "lch"; + lab: { + (...lch: LCH): LAB; + raw: (...lch: LCH) => LAB; + }; + } & route.lch & { + [F in keyof route.lch]: { + raw: route.lch[F]; + }; + }; + hex: { + channels: Channels; + labels: [ + "hex" + ]; + rgb: { + (hex: HEX): RGB; + raw: (hex: HEX) => RGB; + }; + } & route.hex & { + [F in keyof route.hex]: { + raw: route.hex[F]; + }; + }; + ansi16: { + channels: Channels; + labels: [ + "ansi16" + ]; + rgb: { + (ansi16: ANSI16): RGB; + raw: (ansi16: ANSI16) => RGB; + }; + } & route.ansi16 & { + [F in keyof route.ansi16]: { + raw: route.ansi16[F]; + }; + }; + ansi256: { + channels: Channels; + labels: [ + "ansi256" + ]; + rgb: { + (ansi256: ANSI256): RGB; + raw: (ansi256: ANSI256) => RGB; + }; + } & route.ansi256 & { + [F in keyof route.ansi256]: { + raw: route.ansi256[F]; + }; + }; + hcg: { + channels: Channels; + labels: [ + "h", + "c", + "g" + ]; + rgb: { + (...hcg: HCG): RGB; + raw: (...hcg: HCG) => RGB; + }; + hsv: { + (...hcg: HCG): HSV; + raw: (...hcg: HCG) => HSV; + }; + hwb: { + (...hcg: HCG): HWB; + raw: (...hcg: HCG) => HWB; + }; + } & route.hcg & { + [F in keyof route.hcg]: { + raw: route.hcg[F]; + }; + }; + apple: { + channels: Channels; + labels: [ + "r16", + "g16", + "b16" + ]; + rgb: { + (...apple: Apple): RGB; + raw: (...apple: Apple) => RGB; + }; + } & route.apple & { + [F in keyof route.apple]: { + raw: route.apple[F]; + }; + }; + gray: { + channels: Channels; + labels: [ + "gray" + ]; + rgb: { + (...gray: Gray): RGB; + raw: (...gray: Gray) => RGB; + }; + hsl: { + (...gray: Gray): HSL; + raw: (...gray: Gray) => HSL; + }; + hsv: { + (...gray: Gray): HSV; + raw: (...gray: Gray) => HSV; + }; + hwb: { + (...gray: Gray): HWB; + raw: (...gray: Gray) => HWB; + }; + cmyk: { + (...gray: Gray): CMYK; + raw: (...gray: Gray) => CMYK; + }; + lab: { + (...gray: Gray): LAB; + raw: (...gray: Gray) => LAB; + }; + hex: { + (...gray: Gray): HEX; + raw: (...gray: Gray) => HEX; + }; + } & route.gray & { + [F in keyof route.gray]: { + raw: route.gray[F]; + }; + }; +}; +declare const convert: Convert; +export type ColorLike = ColorInstance | string | ArrayLike | number | Record; +export type ColorJson = { + model: string; + color: number[]; + valpha: number; +}; +export type ColorObject = { + alpha?: number | undefined; +} & Record; +// eslint-disable-next-line @typescript-eslint/consistent-type-definitions +export interface ColorInstance { + toString(): string; + // eslint-disable-next-line @typescript-eslint/naming-convention + toJSON(): ColorJson; + string(places?: number): string; + percentString(places?: number): string; + array(): number[]; + object(): ColorObject; + unitArray(): number[]; + unitObject(): { + r: number; + g: number; + b: number; + alpha?: number | undefined; + }; + round(places?: number): ColorInstance; + alpha(): number; + alpha(value: number): ColorInstance; + red(): number; + red(value: number): ColorInstance; + green(): number; + green(value: number): ColorInstance; + blue(): number; + blue(value: number): ColorInstance; + hue(): number; + hue(value: number): ColorInstance; + saturationl(): number; + saturationl(value: number): ColorInstance; + lightness(): number; + lightness(value: number): ColorInstance; + saturationv(): number; + saturationv(value: number): ColorInstance; + value(): number; + value(value: number): ColorInstance; + chroma(): number; + chroma(value: number): ColorInstance; + gray(): number; + gray(value: number): ColorInstance; + white(): number; + white(value: number): ColorInstance; + wblack(): number; + wblack(value: number): ColorInstance; + cyan(): number; + cyan(value: number): ColorInstance; + magenta(): number; + magenta(value: number): ColorInstance; + yellow(): number; + yellow(value: number): ColorInstance; + black(): number; + black(value: number): ColorInstance; + x(): number; + x(value: number): ColorInstance; + y(): number; + y(value: number): ColorInstance; + z(): number; + z(value: number): ColorInstance; + l(): number; + l(value: number): ColorInstance; + a(): number; + a(value: number): ColorInstance; + b(): number; + b(value: number): ColorInstance; + keyword(): string; + keyword(value: V): ColorInstance; + hex(): string; + hex(value: V): ColorInstance; + hexa(): string; + hexa(value: V): ColorInstance; + rgbNumber(): number; + luminosity(): number; + contrast(color2: ColorInstance): number; + level(color2: ColorInstance): "AAA" | "AA" | ""; + isDark(): boolean; + isLight(): boolean; + negate(): ColorInstance; + lighten(ratio: number): ColorInstance; + darken(ratio: number): ColorInstance; + saturate(ratio: number): ColorInstance; + desaturate(ratio: number): ColorInstance; + whiten(ratio: number): ColorInstance; + blacken(ratio: number): ColorInstance; + grayscale(): ColorInstance; + fade(ratio: number): ColorInstance; + opaquer(ratio: number): ColorInstance; + rotate(degrees: number): ColorInstance; + mix(mixinColor: ColorInstance, weight?: number): ColorInstance; + rgb(...arguments_: number[]): ColorInstance; + hsl(...arguments_: number[]): ColorInstance; + hsv(...arguments_: number[]): ColorInstance; + hwb(...arguments_: number[]): ColorInstance; + cmyk(...arguments_: number[]): ColorInstance; + xyz(...arguments_: number[]): ColorInstance; + lab(...arguments_: number[]): ColorInstance; + lch(...arguments_: number[]): ColorInstance; + ansi16(...arguments_: number[]): ColorInstance; + ansi256(...arguments_: number[]): ColorInstance; + hcg(...arguments_: number[]): ColorInstance; + apple(...arguments_: number[]): ColorInstance; +} +export type ColorConstructor = { + (object?: ColorLike, model?: keyof (typeof convert)): ColorInstance; + new (object?: ColorLike, model?: keyof (typeof convert)): ColorInstance; + rgb(...value: number[]): ColorInstance; + rgb(color: ColorLike): ColorInstance; + hsl(...value: number[]): ColorInstance; + hsl(color: ColorLike): ColorInstance; + hsv(...value: number[]): ColorInstance; + hsv(color: ColorLike): ColorInstance; + hwb(...value: number[]): ColorInstance; + hwb(color: ColorLike): ColorInstance; + cmyk(...value: number[]): ColorInstance; + cmyk(color: ColorLike): ColorInstance; + xyz(...value: number[]): ColorInstance; + xyz(color: ColorLike): ColorInstance; + lab(...value: number[]): ColorInstance; + lab(color: ColorLike): ColorInstance; + lch(...value: number[]): ColorInstance; + lch(color: ColorLike): ColorInstance; + ansi16(...value: number[]): ColorInstance; + ansi16(color: ColorLike): ColorInstance; + ansi256(...value: number[]): ColorInstance; + ansi256(color: ColorLike): ColorInstance; + hcg(...value: number[]): ColorInstance; + hcg(color: ColorLike): ColorInstance; + apple(...value: number[]): ColorInstance; + apple(color: ColorLike): ColorInstance; +}; +// eslint-disable-next-line @typescript-eslint/naming-convention +declare const Color: ColorConstructor; + +export { + Color as default, +}; + +export {}; diff --git a/node_modules/@img/colour/package.json b/node_modules/@img/colour/package.json new file mode 100644 index 0000000..38887d1 --- /dev/null +++ b/node_modules/@img/colour/package.json @@ -0,0 +1,58 @@ +{ + "name": "@img/colour", + "version": "1.1.0", + "description": "The ESM-only 'color' package made compatible for use with CommonJS runtimes", + "license": "MIT", + "main": "index.cjs", + "types": "index.d.ts", + "exports": { + ".": { + "types": "./index.d.ts", + "require": "./index.cjs", + "default": "./index.cjs" + }, + "./package.json": "./package.json" + }, + "authors": [ + "Heather Arthur ", + "Josh Junon ", + "Maxime Thirouin", + "Dyma Ywanov ", + "LitoMore (https://github.com/LitoMore)" + ], + "engines": { + "node": ">=18" + }, + "files": [ + "color.cjs", + "index.d.ts" + ], + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/lovell/colour.git" + }, + "type": "commonjs", + "keywords": [ + "color", + "colour", + "cjs", + "commonjs" + ], + "scripts": { + "build:cjs": "esbuild node_modules/color/index.js --bundle --platform=node --outfile=color.cjs", + "build:dts": "dts-bundle-generator ./dts-src.ts -o index.d.ts --project tsconfig.build.json --external-inlines color --external-inlines color-convert --export-referenced-types=false", + "build": "npm run build:cjs && npm run build:dts", + "test": "node --test" + }, + "devDependencies": { + "color": "5.0.3", + "color-convert": "3.1.3", + "color-name": "2.1.0", + "color-string": "2.1.4", + "dts-bundle-generator": "^9.5.1", + "esbuild": "^0.27.3" + } +} diff --git a/node_modules/@img/sharp-libvips-linux-x64/README.md b/node_modules/@img/sharp-libvips-linux-x64/README.md new file mode 100644 index 0000000..2574795 --- /dev/null +++ b/node_modules/@img/sharp-libvips-linux-x64/README.md @@ -0,0 +1,46 @@ +# `@img/sharp-libvips-linux-x64` + +Prebuilt libvips and dependencies for use with sharp on Linux (glibc) x64. + +## Licensing + +This software contains third-party libraries +used under the terms of the following licenses: + +| Library | Used under the terms of | +|---------------|-----------------------------------------------------------------------------------------------------------| +| aom | BSD 2-Clause + [Alliance for Open Media Patent License 1.0](https://aomedia.org/license/patent-license/) | +| cairo | Mozilla Public License 2.0 | +| cgif | MIT License | +| expat | MIT License | +| fontconfig | [fontconfig License](https://gitlab.freedesktop.org/fontconfig/fontconfig/blob/main/COPYING) (BSD-like) | +| freetype | [freetype License](https://git.savannah.gnu.org/cgit/freetype/freetype2.git/tree/docs/FTL.TXT) (BSD-like) | +| fribidi | LGPLv3 | +| glib | LGPLv3 | +| harfbuzz | MIT License | +| highway | BSD 3-Clause | +| lcms | MIT License | +| libarchive | BSD 2-Clause | +| libexif | LGPLv3 | +| libffi | MIT License | +| libheif | LGPLv3 | +| libimagequant | [BSD 2-Clause](https://github.com/lovell/libimagequant/blob/main/COPYRIGHT) | +| libnsgif | MIT License | +| libpng | [libpng License](https://github.com/pnggroup/libpng/blob/master/LICENSE) | +| librsvg | LGPLv3 | +| libtiff | [libtiff License](https://gitlab.com/libtiff/libtiff/blob/master/LICENSE.md) (BSD-like) | +| libultrahdr | MIT License | +| libvips | LGPLv3 | +| libwebp | New BSD License | +| libxml2 | MIT License | +| mozjpeg | [zlib License, IJG License, BSD 3-Clause](https://github.com/mozilla/mozjpeg/blob/master/LICENSE.md) | +| pango | LGPLv3 | +| pixman | MIT License | +| proxy-libintl | LGPLv3 | +| zlib-ng | [zlib License](https://github.com/zlib-ng/zlib-ng/blob/develop/LICENSE.md) | + +Use of libraries under the terms of the LGPLv3 is via the +"any later version" clause of the LGPLv2 or LGPLv2.1. + +Please report any errors or omissions via +https://github.com/lovell/sharp-libvips/issues/new diff --git a/node_modules/@img/sharp-libvips-linux-x64/lib/glib-2.0/include/glibconfig.h b/node_modules/@img/sharp-libvips-linux-x64/lib/glib-2.0/include/glibconfig.h new file mode 100644 index 0000000..d56f154 --- /dev/null +++ b/node_modules/@img/sharp-libvips-linux-x64/lib/glib-2.0/include/glibconfig.h @@ -0,0 +1,219 @@ +/* glibconfig.h + * + * This is a generated file. Please modify 'glibconfig.h.in' + */ + +#ifndef __GLIBCONFIG_H__ +#define __GLIBCONFIG_H__ + +#include + +#include +#include +#define GLIB_HAVE_ALLOCA_H + +#define GLIB_STATIC_COMPILATION 1 +#define GOBJECT_STATIC_COMPILATION 1 +#define GIO_STATIC_COMPILATION 1 +#define GMODULE_STATIC_COMPILATION 1 +#define GI_STATIC_COMPILATION 1 + +/* Specifies that GLib's g_print*() functions wrap the + * system printf functions. This is useful to know, for example, + * when using glibc's register_printf_function(). + */ +#define GLIB_USING_SYSTEM_PRINTF + +G_BEGIN_DECLS + +#define G_MINFLOAT FLT_MIN +#define G_MAXFLOAT FLT_MAX +#define G_MINDOUBLE DBL_MIN +#define G_MAXDOUBLE DBL_MAX +#define G_MINSHORT SHRT_MIN +#define G_MAXSHORT SHRT_MAX +#define G_MAXUSHORT USHRT_MAX +#define G_MININT INT_MIN +#define G_MAXINT INT_MAX +#define G_MAXUINT UINT_MAX +#define G_MINLONG LONG_MIN +#define G_MAXLONG LONG_MAX +#define G_MAXULONG ULONG_MAX + +typedef signed char gint8; +typedef unsigned char guint8; + +typedef signed short gint16; +typedef unsigned short guint16; + +#define G_GINT16_MODIFIER "h" +#define G_GINT16_FORMAT "hi" +#define G_GUINT16_FORMAT "hu" + + +typedef signed int gint32; +typedef unsigned int guint32; + +#define G_GINT32_MODIFIER "" +#define G_GINT32_FORMAT "i" +#define G_GUINT32_FORMAT "u" + + +#define G_HAVE_GINT64 1 /* deprecated, always true */ + +typedef signed long gint64; +typedef unsigned long guint64; + +#define G_GINT64_CONSTANT(val) (val##L) +#define G_GUINT64_CONSTANT(val) (val##UL) + +#define G_GINT64_MODIFIER "l" +#define G_GINT64_FORMAT "li" +#define G_GUINT64_FORMAT "lu" + + +#define GLIB_SIZEOF_VOID_P 8 +#define GLIB_SIZEOF_LONG 8 +#define GLIB_SIZEOF_SIZE_T 8 +#define GLIB_SIZEOF_SSIZE_T 8 + +typedef signed long gssize; +typedef unsigned long gsize; +#define G_GSIZE_MODIFIER "l" +#define G_GSSIZE_MODIFIER "l" +#define G_GSIZE_FORMAT "lu" +#define G_GSSIZE_FORMAT "li" + +#define G_MAXSIZE G_MAXULONG +#define G_MINSSIZE G_MINLONG +#define G_MAXSSIZE G_MAXLONG + +typedef gint64 goffset; +#define G_MINOFFSET G_MININT64 +#define G_MAXOFFSET G_MAXINT64 + +#define G_GOFFSET_MODIFIER G_GINT64_MODIFIER +#define G_GOFFSET_FORMAT G_GINT64_FORMAT +#define G_GOFFSET_CONSTANT(val) G_GINT64_CONSTANT(val) + +#define G_POLLFD_FORMAT "%d" + +#define GPOINTER_TO_INT(p) ((gint) (glong) (p)) +#define GPOINTER_TO_UINT(p) ((guint) (gulong) (p)) + +#define GINT_TO_POINTER(i) ((gpointer) (glong) (i)) +#define GUINT_TO_POINTER(u) ((gpointer) (gulong) (u)) + +typedef signed long gintptr; +typedef unsigned long guintptr; + +#define G_GINTPTR_MODIFIER "l" +#define G_GINTPTR_FORMAT "li" +#define G_GUINTPTR_FORMAT "lu" + +#define GLIB_MAJOR_VERSION 2 +#define GLIB_MINOR_VERSION 89 +#define GLIB_MICRO_VERSION 1 + +#define G_OS_UNIX + +#define G_VA_COPY va_copy + +#define G_VA_COPY_AS_ARRAY 1 + +#define G_HAVE_ISO_VARARGS 1 + +/* gcc-2.95.x supports both gnu style and ISO varargs, but if -ansi + * is passed ISO vararg support is turned off, and there is no work + * around to turn it on, so we unconditionally turn it off. + */ +#if __GNUC__ == 2 && __GNUC_MINOR__ == 95 +# undef G_HAVE_ISO_VARARGS +#endif + +#define G_HAVE_GROWING_STACK 0 + +#ifndef _MSC_VER +# define G_HAVE_GNUC_VARARGS 1 +#endif + +#if defined(__SUNPRO_C) && (__SUNPRO_C >= 0x590) +#define G_GNUC_INTERNAL __attribute__((visibility("hidden"))) +#elif defined(__SUNPRO_C) && (__SUNPRO_C >= 0x550) +#define G_GNUC_INTERNAL __hidden +#elif defined (__GNUC__) && defined (G_HAVE_GNUC_VISIBILITY) +#define G_GNUC_INTERNAL __attribute__((visibility("hidden"))) +#else +#define G_GNUC_INTERNAL +#endif + +#define G_THREADS_ENABLED +#define G_THREADS_IMPL_POSIX + +#define G_ATOMIC_LOCK_FREE + +#define GINT16_TO_LE(val) ((gint16) (val)) +#define GUINT16_TO_LE(val) ((guint16) (val)) +#define GINT16_TO_BE(val) ((gint16) GUINT16_SWAP_LE_BE (val)) +#define GUINT16_TO_BE(val) (GUINT16_SWAP_LE_BE (val)) + +#define GINT32_TO_LE(val) ((gint32) (val)) +#define GUINT32_TO_LE(val) ((guint32) (val)) +#define GINT32_TO_BE(val) ((gint32) GUINT32_SWAP_LE_BE (val)) +#define GUINT32_TO_BE(val) (GUINT32_SWAP_LE_BE (val)) + +#define GINT64_TO_LE(val) ((gint64) (val)) +#define GUINT64_TO_LE(val) ((guint64) (val)) +#define GINT64_TO_BE(val) ((gint64) GUINT64_SWAP_LE_BE (val)) +#define GUINT64_TO_BE(val) (GUINT64_SWAP_LE_BE (val)) + +#define GLONG_TO_LE(val) ((glong) GINT64_TO_LE (val)) +#define GULONG_TO_LE(val) ((gulong) GUINT64_TO_LE (val)) +#define GLONG_TO_BE(val) ((glong) GINT64_TO_BE (val)) +#define GULONG_TO_BE(val) ((gulong) GUINT64_TO_BE (val)) +#define GINT_TO_LE(val) ((gint) GINT32_TO_LE (val)) +#define GUINT_TO_LE(val) ((guint) GUINT32_TO_LE (val)) +#define GINT_TO_BE(val) ((gint) GINT32_TO_BE (val)) +#define GUINT_TO_BE(val) ((guint) GUINT32_TO_BE (val)) +#define GSIZE_TO_LE(val) ((gsize) GUINT64_TO_LE (val)) +#define GSSIZE_TO_LE(val) ((gssize) GINT64_TO_LE (val)) +#define GSIZE_TO_BE(val) ((gsize) GUINT64_TO_BE (val)) +#define GSSIZE_TO_BE(val) ((gssize) GINT64_TO_BE (val)) +#define G_BYTE_ORDER G_LITTLE_ENDIAN + +#define GLIB_SYSDEF_POLLIN =1 +#define GLIB_SYSDEF_POLLOUT =4 +#define GLIB_SYSDEF_POLLPRI =2 +#define GLIB_SYSDEF_POLLHUP =16 +#define GLIB_SYSDEF_POLLERR =8 +#define GLIB_SYSDEF_POLLNVAL =32 + +/* No way to disable deprecation warnings for macros, so only emit deprecation + * warnings on platforms where usage of this macro is broken */ +#if defined(__APPLE__) || defined(_MSC_VER) || defined(__CYGWIN__) +#define G_MODULE_SUFFIX "so" GLIB_DEPRECATED_MACRO_IN_2_76 +#else +#define G_MODULE_SUFFIX "so" +#endif + +typedef int GPid; +#define G_PID_FORMAT "i" + +#define GLIB_SYSDEF_AF_UNIX 1 +#define GLIB_SYSDEF_AF_INET 2 +#define GLIB_SYSDEF_AF_INET6 10 + +#define GLIB_SYSDEF_MSG_OOB 1 +#define GLIB_SYSDEF_MSG_PEEK 2 +#define GLIB_SYSDEF_MSG_DONTROUTE 4 + +#define G_DIR_SEPARATOR '/' +#define G_DIR_SEPARATOR_S "/" +#define G_SEARCHPATH_SEPARATOR ':' +#define G_SEARCHPATH_SEPARATOR_S ":" + +#undef G_HAVE_FREE_SIZED + +G_END_DECLS + +#endif /* __GLIBCONFIG_H__ */ diff --git a/node_modules/@img/sharp-libvips-linux-x64/lib/index.js b/node_modules/@img/sharp-libvips-linux-x64/lib/index.js new file mode 100644 index 0000000..5092b4d --- /dev/null +++ b/node_modules/@img/sharp-libvips-linux-x64/lib/index.js @@ -0,0 +1 @@ +module.exports = __dirname; diff --git a/node_modules/@img/sharp-libvips-linux-x64/lib/libvips-cpp.so.8.18.3 b/node_modules/@img/sharp-libvips-linux-x64/lib/libvips-cpp.so.8.18.3 new file mode 100644 index 0000000..3f5412e Binary files /dev/null and b/node_modules/@img/sharp-libvips-linux-x64/lib/libvips-cpp.so.8.18.3 differ diff --git a/node_modules/@img/sharp-libvips-linux-x64/package.json b/node_modules/@img/sharp-libvips-linux-x64/package.json new file mode 100644 index 0000000..a42c669 --- /dev/null +++ b/node_modules/@img/sharp-libvips-linux-x64/package.json @@ -0,0 +1,43 @@ +{ + "name": "@img/sharp-libvips-linux-x64", + "version": "1.3.2", + "description": "Prebuilt libvips and dependencies for use with sharp on Linux (glibc) x64", + "author": "Lovell Fuller ", + "homepage": "https://sharp.pixelplumbing.com", + "repository": { + "type": "git", + "url": "git+https://github.com/lovell/sharp-libvips.git", + "directory": "npm/linux-x64" + }, + "license": "LGPL-3.0-or-later", + "funding": { + "url": "https://opencollective.com/libvips" + }, + "preferUnplugged": true, + "publishConfig": { + "access": "public" + }, + "files": [ + "lib", + "versions.json" + ], + "type": "commonjs", + "exports": { + "./lib": "./lib/index.js", + "./package": "./package.json", + "./versions": "./versions.json", + "./binary": "./lib/libvips-cpp.so.8.18.3" + }, + "config": { + "glibc": ">=2.28" + }, + "os": [ + "linux" + ], + "libc": [ + "glibc" + ], + "cpu": [ + "x64" + ] +} diff --git a/node_modules/@img/sharp-libvips-linux-x64/versions.json b/node_modules/@img/sharp-libvips-linux-x64/versions.json new file mode 100644 index 0000000..1e0a788 --- /dev/null +++ b/node_modules/@img/sharp-libvips-linux-x64/versions.json @@ -0,0 +1,30 @@ +{ + "aom": "3.14.1", + "archive": "3.8.8", + "cairo": "1.18.4", + "cgif": "0.5.3", + "exif": "0.6.26", + "expat": "2.8.2", + "ffi": "3.6.0", + "fontconfig": "2.18.1", + "freetype": "2.14.3", + "fribidi": "1.0.16", + "glib": "2.89.1", + "harfbuzz": "14.2.1", + "heif": "1.23.1", + "highway": "1.4.0", + "imagequant": "2.4.1", + "lcms": "2.19.1", + "mozjpeg": "0826579", + "pango": "1.58.0", + "pixman": "0.46.4", + "png": "1.6.58", + "proxy-libintl": "0.5", + "rsvg": "2.62.90", + "tiff": "d01a94b", + "uhdr": "1acdbed", + "vips": "8.18.3", + "webp": "1.6.0", + "xml2": "2.15.3", + "zlib-ng": "2.3.3" +} \ No newline at end of file diff --git a/node_modules/@img/sharp-libvips-linuxmusl-x64/README.md b/node_modules/@img/sharp-libvips-linuxmusl-x64/README.md new file mode 100644 index 0000000..ded5e42 --- /dev/null +++ b/node_modules/@img/sharp-libvips-linuxmusl-x64/README.md @@ -0,0 +1,46 @@ +# `@img/sharp-libvips-linuxmusl-x64` + +Prebuilt libvips and dependencies for use with sharp on Linux (musl) x64. + +## Licensing + +This software contains third-party libraries +used under the terms of the following licenses: + +| Library | Used under the terms of | +|---------------|-----------------------------------------------------------------------------------------------------------| +| aom | BSD 2-Clause + [Alliance for Open Media Patent License 1.0](https://aomedia.org/license/patent-license/) | +| cairo | Mozilla Public License 2.0 | +| cgif | MIT License | +| expat | MIT License | +| fontconfig | [fontconfig License](https://gitlab.freedesktop.org/fontconfig/fontconfig/blob/main/COPYING) (BSD-like) | +| freetype | [freetype License](https://git.savannah.gnu.org/cgit/freetype/freetype2.git/tree/docs/FTL.TXT) (BSD-like) | +| fribidi | LGPLv3 | +| glib | LGPLv3 | +| harfbuzz | MIT License | +| highway | BSD 3-Clause | +| lcms | MIT License | +| libarchive | BSD 2-Clause | +| libexif | LGPLv3 | +| libffi | MIT License | +| libheif | LGPLv3 | +| libimagequant | [BSD 2-Clause](https://github.com/lovell/libimagequant/blob/main/COPYRIGHT) | +| libnsgif | MIT License | +| libpng | [libpng License](https://github.com/pnggroup/libpng/blob/master/LICENSE) | +| librsvg | LGPLv3 | +| libtiff | [libtiff License](https://gitlab.com/libtiff/libtiff/blob/master/LICENSE.md) (BSD-like) | +| libultrahdr | MIT License | +| libvips | LGPLv3 | +| libwebp | New BSD License | +| libxml2 | MIT License | +| mozjpeg | [zlib License, IJG License, BSD 3-Clause](https://github.com/mozilla/mozjpeg/blob/master/LICENSE.md) | +| pango | LGPLv3 | +| pixman | MIT License | +| proxy-libintl | LGPLv3 | +| zlib-ng | [zlib License](https://github.com/zlib-ng/zlib-ng/blob/develop/LICENSE.md) | + +Use of libraries under the terms of the LGPLv3 is via the +"any later version" clause of the LGPLv2 or LGPLv2.1. + +Please report any errors or omissions via +https://github.com/lovell/sharp-libvips/issues/new diff --git a/node_modules/@img/sharp-libvips-linuxmusl-x64/lib/glib-2.0/include/glibconfig.h b/node_modules/@img/sharp-libvips-linuxmusl-x64/lib/glib-2.0/include/glibconfig.h new file mode 100644 index 0000000..d56f154 --- /dev/null +++ b/node_modules/@img/sharp-libvips-linuxmusl-x64/lib/glib-2.0/include/glibconfig.h @@ -0,0 +1,219 @@ +/* glibconfig.h + * + * This is a generated file. Please modify 'glibconfig.h.in' + */ + +#ifndef __GLIBCONFIG_H__ +#define __GLIBCONFIG_H__ + +#include + +#include +#include +#define GLIB_HAVE_ALLOCA_H + +#define GLIB_STATIC_COMPILATION 1 +#define GOBJECT_STATIC_COMPILATION 1 +#define GIO_STATIC_COMPILATION 1 +#define GMODULE_STATIC_COMPILATION 1 +#define GI_STATIC_COMPILATION 1 + +/* Specifies that GLib's g_print*() functions wrap the + * system printf functions. This is useful to know, for example, + * when using glibc's register_printf_function(). + */ +#define GLIB_USING_SYSTEM_PRINTF + +G_BEGIN_DECLS + +#define G_MINFLOAT FLT_MIN +#define G_MAXFLOAT FLT_MAX +#define G_MINDOUBLE DBL_MIN +#define G_MAXDOUBLE DBL_MAX +#define G_MINSHORT SHRT_MIN +#define G_MAXSHORT SHRT_MAX +#define G_MAXUSHORT USHRT_MAX +#define G_MININT INT_MIN +#define G_MAXINT INT_MAX +#define G_MAXUINT UINT_MAX +#define G_MINLONG LONG_MIN +#define G_MAXLONG LONG_MAX +#define G_MAXULONG ULONG_MAX + +typedef signed char gint8; +typedef unsigned char guint8; + +typedef signed short gint16; +typedef unsigned short guint16; + +#define G_GINT16_MODIFIER "h" +#define G_GINT16_FORMAT "hi" +#define G_GUINT16_FORMAT "hu" + + +typedef signed int gint32; +typedef unsigned int guint32; + +#define G_GINT32_MODIFIER "" +#define G_GINT32_FORMAT "i" +#define G_GUINT32_FORMAT "u" + + +#define G_HAVE_GINT64 1 /* deprecated, always true */ + +typedef signed long gint64; +typedef unsigned long guint64; + +#define G_GINT64_CONSTANT(val) (val##L) +#define G_GUINT64_CONSTANT(val) (val##UL) + +#define G_GINT64_MODIFIER "l" +#define G_GINT64_FORMAT "li" +#define G_GUINT64_FORMAT "lu" + + +#define GLIB_SIZEOF_VOID_P 8 +#define GLIB_SIZEOF_LONG 8 +#define GLIB_SIZEOF_SIZE_T 8 +#define GLIB_SIZEOF_SSIZE_T 8 + +typedef signed long gssize; +typedef unsigned long gsize; +#define G_GSIZE_MODIFIER "l" +#define G_GSSIZE_MODIFIER "l" +#define G_GSIZE_FORMAT "lu" +#define G_GSSIZE_FORMAT "li" + +#define G_MAXSIZE G_MAXULONG +#define G_MINSSIZE G_MINLONG +#define G_MAXSSIZE G_MAXLONG + +typedef gint64 goffset; +#define G_MINOFFSET G_MININT64 +#define G_MAXOFFSET G_MAXINT64 + +#define G_GOFFSET_MODIFIER G_GINT64_MODIFIER +#define G_GOFFSET_FORMAT G_GINT64_FORMAT +#define G_GOFFSET_CONSTANT(val) G_GINT64_CONSTANT(val) + +#define G_POLLFD_FORMAT "%d" + +#define GPOINTER_TO_INT(p) ((gint) (glong) (p)) +#define GPOINTER_TO_UINT(p) ((guint) (gulong) (p)) + +#define GINT_TO_POINTER(i) ((gpointer) (glong) (i)) +#define GUINT_TO_POINTER(u) ((gpointer) (gulong) (u)) + +typedef signed long gintptr; +typedef unsigned long guintptr; + +#define G_GINTPTR_MODIFIER "l" +#define G_GINTPTR_FORMAT "li" +#define G_GUINTPTR_FORMAT "lu" + +#define GLIB_MAJOR_VERSION 2 +#define GLIB_MINOR_VERSION 89 +#define GLIB_MICRO_VERSION 1 + +#define G_OS_UNIX + +#define G_VA_COPY va_copy + +#define G_VA_COPY_AS_ARRAY 1 + +#define G_HAVE_ISO_VARARGS 1 + +/* gcc-2.95.x supports both gnu style and ISO varargs, but if -ansi + * is passed ISO vararg support is turned off, and there is no work + * around to turn it on, so we unconditionally turn it off. + */ +#if __GNUC__ == 2 && __GNUC_MINOR__ == 95 +# undef G_HAVE_ISO_VARARGS +#endif + +#define G_HAVE_GROWING_STACK 0 + +#ifndef _MSC_VER +# define G_HAVE_GNUC_VARARGS 1 +#endif + +#if defined(__SUNPRO_C) && (__SUNPRO_C >= 0x590) +#define G_GNUC_INTERNAL __attribute__((visibility("hidden"))) +#elif defined(__SUNPRO_C) && (__SUNPRO_C >= 0x550) +#define G_GNUC_INTERNAL __hidden +#elif defined (__GNUC__) && defined (G_HAVE_GNUC_VISIBILITY) +#define G_GNUC_INTERNAL __attribute__((visibility("hidden"))) +#else +#define G_GNUC_INTERNAL +#endif + +#define G_THREADS_ENABLED +#define G_THREADS_IMPL_POSIX + +#define G_ATOMIC_LOCK_FREE + +#define GINT16_TO_LE(val) ((gint16) (val)) +#define GUINT16_TO_LE(val) ((guint16) (val)) +#define GINT16_TO_BE(val) ((gint16) GUINT16_SWAP_LE_BE (val)) +#define GUINT16_TO_BE(val) (GUINT16_SWAP_LE_BE (val)) + +#define GINT32_TO_LE(val) ((gint32) (val)) +#define GUINT32_TO_LE(val) ((guint32) (val)) +#define GINT32_TO_BE(val) ((gint32) GUINT32_SWAP_LE_BE (val)) +#define GUINT32_TO_BE(val) (GUINT32_SWAP_LE_BE (val)) + +#define GINT64_TO_LE(val) ((gint64) (val)) +#define GUINT64_TO_LE(val) ((guint64) (val)) +#define GINT64_TO_BE(val) ((gint64) GUINT64_SWAP_LE_BE (val)) +#define GUINT64_TO_BE(val) (GUINT64_SWAP_LE_BE (val)) + +#define GLONG_TO_LE(val) ((glong) GINT64_TO_LE (val)) +#define GULONG_TO_LE(val) ((gulong) GUINT64_TO_LE (val)) +#define GLONG_TO_BE(val) ((glong) GINT64_TO_BE (val)) +#define GULONG_TO_BE(val) ((gulong) GUINT64_TO_BE (val)) +#define GINT_TO_LE(val) ((gint) GINT32_TO_LE (val)) +#define GUINT_TO_LE(val) ((guint) GUINT32_TO_LE (val)) +#define GINT_TO_BE(val) ((gint) GINT32_TO_BE (val)) +#define GUINT_TO_BE(val) ((guint) GUINT32_TO_BE (val)) +#define GSIZE_TO_LE(val) ((gsize) GUINT64_TO_LE (val)) +#define GSSIZE_TO_LE(val) ((gssize) GINT64_TO_LE (val)) +#define GSIZE_TO_BE(val) ((gsize) GUINT64_TO_BE (val)) +#define GSSIZE_TO_BE(val) ((gssize) GINT64_TO_BE (val)) +#define G_BYTE_ORDER G_LITTLE_ENDIAN + +#define GLIB_SYSDEF_POLLIN =1 +#define GLIB_SYSDEF_POLLOUT =4 +#define GLIB_SYSDEF_POLLPRI =2 +#define GLIB_SYSDEF_POLLHUP =16 +#define GLIB_SYSDEF_POLLERR =8 +#define GLIB_SYSDEF_POLLNVAL =32 + +/* No way to disable deprecation warnings for macros, so only emit deprecation + * warnings on platforms where usage of this macro is broken */ +#if defined(__APPLE__) || defined(_MSC_VER) || defined(__CYGWIN__) +#define G_MODULE_SUFFIX "so" GLIB_DEPRECATED_MACRO_IN_2_76 +#else +#define G_MODULE_SUFFIX "so" +#endif + +typedef int GPid; +#define G_PID_FORMAT "i" + +#define GLIB_SYSDEF_AF_UNIX 1 +#define GLIB_SYSDEF_AF_INET 2 +#define GLIB_SYSDEF_AF_INET6 10 + +#define GLIB_SYSDEF_MSG_OOB 1 +#define GLIB_SYSDEF_MSG_PEEK 2 +#define GLIB_SYSDEF_MSG_DONTROUTE 4 + +#define G_DIR_SEPARATOR '/' +#define G_DIR_SEPARATOR_S "/" +#define G_SEARCHPATH_SEPARATOR ':' +#define G_SEARCHPATH_SEPARATOR_S ":" + +#undef G_HAVE_FREE_SIZED + +G_END_DECLS + +#endif /* __GLIBCONFIG_H__ */ diff --git a/node_modules/@img/sharp-libvips-linuxmusl-x64/lib/index.js b/node_modules/@img/sharp-libvips-linuxmusl-x64/lib/index.js new file mode 100644 index 0000000..5092b4d --- /dev/null +++ b/node_modules/@img/sharp-libvips-linuxmusl-x64/lib/index.js @@ -0,0 +1 @@ +module.exports = __dirname; diff --git a/node_modules/@img/sharp-libvips-linuxmusl-x64/lib/libvips-cpp.so.8.18.3 b/node_modules/@img/sharp-libvips-linuxmusl-x64/lib/libvips-cpp.so.8.18.3 new file mode 100644 index 0000000..251b4cd Binary files /dev/null and b/node_modules/@img/sharp-libvips-linuxmusl-x64/lib/libvips-cpp.so.8.18.3 differ diff --git a/node_modules/@img/sharp-libvips-linuxmusl-x64/package.json b/node_modules/@img/sharp-libvips-linuxmusl-x64/package.json new file mode 100644 index 0000000..f23e7d4 --- /dev/null +++ b/node_modules/@img/sharp-libvips-linuxmusl-x64/package.json @@ -0,0 +1,43 @@ +{ + "name": "@img/sharp-libvips-linuxmusl-x64", + "version": "1.3.2", + "description": "Prebuilt libvips and dependencies for use with sharp on Linux (musl) x64", + "author": "Lovell Fuller ", + "homepage": "https://sharp.pixelplumbing.com", + "repository": { + "type": "git", + "url": "git+https://github.com/lovell/sharp-libvips.git", + "directory": "npm/linuxmusl-x64" + }, + "license": "LGPL-3.0-or-later", + "funding": { + "url": "https://opencollective.com/libvips" + }, + "preferUnplugged": true, + "publishConfig": { + "access": "public" + }, + "files": [ + "lib", + "versions.json" + ], + "type": "commonjs", + "exports": { + "./lib": "./lib/index.js", + "./package": "./package.json", + "./versions": "./versions.json", + "./binary": "./lib/libvips-cpp.so.8.18.3" + }, + "config": { + "musl": ">=1.2.5" + }, + "os": [ + "linux" + ], + "libc": [ + "musl" + ], + "cpu": [ + "x64" + ] +} diff --git a/node_modules/@img/sharp-libvips-linuxmusl-x64/versions.json b/node_modules/@img/sharp-libvips-linuxmusl-x64/versions.json new file mode 100644 index 0000000..1e0a788 --- /dev/null +++ b/node_modules/@img/sharp-libvips-linuxmusl-x64/versions.json @@ -0,0 +1,30 @@ +{ + "aom": "3.14.1", + "archive": "3.8.8", + "cairo": "1.18.4", + "cgif": "0.5.3", + "exif": "0.6.26", + "expat": "2.8.2", + "ffi": "3.6.0", + "fontconfig": "2.18.1", + "freetype": "2.14.3", + "fribidi": "1.0.16", + "glib": "2.89.1", + "harfbuzz": "14.2.1", + "heif": "1.23.1", + "highway": "1.4.0", + "imagequant": "2.4.1", + "lcms": "2.19.1", + "mozjpeg": "0826579", + "pango": "1.58.0", + "pixman": "0.46.4", + "png": "1.6.58", + "proxy-libintl": "0.5", + "rsvg": "2.62.90", + "tiff": "d01a94b", + "uhdr": "1acdbed", + "vips": "8.18.3", + "webp": "1.6.0", + "xml2": "2.15.3", + "zlib-ng": "2.3.3" +} \ No newline at end of file diff --git a/node_modules/@img/sharp-linux-x64/LICENSE b/node_modules/@img/sharp-linux-x64/LICENSE new file mode 100644 index 0000000..37ec93a --- /dev/null +++ b/node_modules/@img/sharp-linux-x64/LICENSE @@ -0,0 +1,191 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and +distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright +owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities +that control, are controlled by, or are under common control with that entity. +For the purposes of this definition, "control" means (i) the power, direct or +indirect, to cause the direction or management of such entity, whether by +contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the +outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising +permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including +but not limited to software source code, documentation source, and configuration +files. + +"Object" form shall mean any form resulting from mechanical transformation or +translation of a Source form, including but not limited to compiled object code, +generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made +available under the License, as indicated by a copyright notice that is included +in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that +is based on (or derived from) the Work and for which the editorial revisions, +annotations, elaborations, or other modifications represent, as a whole, an +original work of authorship. For the purposes of this License, Derivative Works +shall not include works that remain separable from, or merely link (or bind by +name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version +of the Work and any modifications or additions to that Work or Derivative Works +thereof, that is intentionally submitted to Licensor for inclusion in the Work +by the copyright owner or by an individual or Legal Entity authorized to submit +on behalf of the copyright owner. For the purposes of this definition, +"submitted" means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, and +issue tracking systems that are managed by, or on behalf of, the Licensor for +the purpose of discussing and improving the Work, but excluding communication +that is conspicuously marked or otherwise designated in writing by the copyright +owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf +of whom a Contribution has been received by Licensor and subsequently +incorporated within the Work. + +2. Grant of Copyright License. + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the Work and such +Derivative Works in Source or Object form. + +3. Grant of Patent License. + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable (except as stated in this section) patent license to make, have +made, use, offer to sell, sell, import, and otherwise transfer the Work, where +such license applies only to those patent claims licensable by such Contributor +that are necessarily infringed by their Contribution(s) alone or by combination +of their Contribution(s) with the Work to which such Contribution(s) was +submitted. If You institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work or a +Contribution incorporated within the Work constitutes direct or contributory +patent infringement, then any patent licenses granted to You under this License +for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. + +You may reproduce and distribute copies of the Work or Derivative Works thereof +in any medium, with or without modifications, and in Source or Object form, +provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of +this License; and +You must cause any modified files to carry prominent notices stating that You +changed the files; and +You must retain, in the Source form of any Derivative Works that You distribute, +all copyright, patent, trademark, and attribution notices from the Source form +of the Work, excluding those notices that do not pertain to any part of the +Derivative Works; and +If the Work includes a "NOTICE" text file as part of its distribution, then any +Derivative Works that You distribute must include a readable copy of the +attribution notices contained within such NOTICE file, excluding those notices +that do not pertain to any part of the Derivative Works, in at least one of the +following places: within a NOTICE text file distributed as part of the +Derivative Works; within the Source form or documentation, if provided along +with the Derivative Works; or, within a display generated by the Derivative +Works, if and wherever such third-party notices normally appear. The contents of +the NOTICE file are for informational purposes only and do not modify the +License. You may add Your own attribution notices within Derivative Works that +You distribute, alongside or as an addendum to the NOTICE text from the Work, +provided that such additional attribution notices cannot be construed as +modifying the License. +You may add Your own copyright statement to Your modifications and may provide +additional or different license terms and conditions for use, reproduction, or +distribution of Your modifications, or for any such Derivative Works as a whole, +provided Your use, reproduction, and distribution of the Work otherwise complies +with the conditions stated in this License. + +5. Submission of Contributions. + +Unless You explicitly state otherwise, any Contribution intentionally submitted +for inclusion in the Work by You to the Licensor shall be under the terms and +conditions of this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify the terms of +any separate license agreement you may have executed with Licensor regarding +such Contributions. + +6. Trademarks. + +This License does not grant permission to use the trade names, trademarks, +service marks, or product names of the Licensor, except as required for +reasonable and customary use in describing the origin of the Work and +reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. + +Unless required by applicable law or agreed to in writing, Licensor provides the +Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, +including, without limitation, any warranties or conditions of TITLE, +NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are +solely responsible for determining the appropriateness of using or +redistributing the Work and assume any risks associated with Your exercise of +permissions under this License. + +8. Limitation of Liability. + +In no event and under no legal theory, whether in tort (including negligence), +contract, or otherwise, unless required by applicable law (such as deliberate +and grossly negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, incidental, +or consequential damages of any character arising as a result of this License or +out of the use or inability to use the Work (including but not limited to +damages for loss of goodwill, work stoppage, computer failure or malfunction, or +any and all other commercial damages or losses), even if such Contributor has +been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. + +While redistributing the Work or Derivative Works thereof, You may choose to +offer, and charge a fee for, acceptance of support, warranty, indemnity, or +other liability obligations and/or rights consistent with this License. However, +in accepting such obligations, You may act only on Your own behalf and on Your +sole responsibility, not on behalf of any other Contributor, and only if You +agree to indemnify, defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason of your +accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work + +To apply the Apache License to your work, attach the following boilerplate +notice, with the fields enclosed by brackets "[]" replaced with your own +identifying information. (Don't include the brackets!) The text should be +enclosed in the appropriate comment syntax for the file format. We also +recommend that a file or class name and description of purpose be included on +the same "printed page" as the copyright notice for easier identification within +third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@img/sharp-linux-x64/README.md b/node_modules/@img/sharp-linux-x64/README.md new file mode 100644 index 0000000..cae31de --- /dev/null +++ b/node_modules/@img/sharp-linux-x64/README.md @@ -0,0 +1,18 @@ +# `@img/sharp-linux-x64` + +Prebuilt sharp for use with Linux (glibc) x64. + +## Licensing + +Copyright 2013 Lovell Fuller and others. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +[https://www.apache.org/licenses/LICENSE-2.0](https://www.apache.org/licenses/LICENSE-2.0) + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/node_modules/@img/sharp-linux-x64/index.cjs b/node_modules/@img/sharp-linux-x64/index.cjs new file mode 100644 index 0000000..ed12ec0 --- /dev/null +++ b/node_modules/@img/sharp-linux-x64/index.cjs @@ -0,0 +1,2 @@ +try { require.resolve('@img/sharp-libvips-linux-x64/binary'); } catch {} +module.exports = require('./lib/sharp-linux-x64-0.35.3.node'); \ No newline at end of file diff --git a/node_modules/@img/sharp-linux-x64/lib/sharp-linux-x64-0.35.3.node b/node_modules/@img/sharp-linux-x64/lib/sharp-linux-x64-0.35.3.node new file mode 100644 index 0000000..00aa9b4 Binary files /dev/null and b/node_modules/@img/sharp-linux-x64/lib/sharp-linux-x64-0.35.3.node differ diff --git a/node_modules/@img/sharp-linux-x64/package.json b/node_modules/@img/sharp-linux-x64/package.json new file mode 100644 index 0000000..cb5ad42 --- /dev/null +++ b/node_modules/@img/sharp-linux-x64/package.json @@ -0,0 +1,47 @@ +{ + "name": "@img/sharp-linux-x64", + "version": "0.35.3", + "description": "Prebuilt sharp for use with Linux (glibc) x64", + "author": "Lovell Fuller ", + "homepage": "https://sharp.pixelplumbing.com", + "repository": { + "type": "git", + "url": "git+https://github.com/lovell/sharp.git", + "directory": "npm/linux-x64" + }, + "license": "Apache-2.0", + "funding": { + "url": "https://opencollective.com/libvips" + }, + "preferUnplugged": true, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.3.2" + }, + "files": [ + "index.cjs", + "lib" + ], + "publishConfig": { + "access": "public" + }, + "type": "commonjs", + "exports": { + "./sharp.node": "./index.cjs", + "./package": "./package.json" + }, + "engines": { + "node": ">=20.9.0" + }, + "config": { + "glibc": ">=2.28" + }, + "os": [ + "linux" + ], + "libc": [ + "glibc" + ], + "cpu": [ + "x64" + ] +} diff --git a/node_modules/@img/sharp-linuxmusl-x64/LICENSE b/node_modules/@img/sharp-linuxmusl-x64/LICENSE new file mode 100644 index 0000000..37ec93a --- /dev/null +++ b/node_modules/@img/sharp-linuxmusl-x64/LICENSE @@ -0,0 +1,191 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and +distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright +owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities +that control, are controlled by, or are under common control with that entity. +For the purposes of this definition, "control" means (i) the power, direct or +indirect, to cause the direction or management of such entity, whether by +contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the +outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising +permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including +but not limited to software source code, documentation source, and configuration +files. + +"Object" form shall mean any form resulting from mechanical transformation or +translation of a Source form, including but not limited to compiled object code, +generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made +available under the License, as indicated by a copyright notice that is included +in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that +is based on (or derived from) the Work and for which the editorial revisions, +annotations, elaborations, or other modifications represent, as a whole, an +original work of authorship. For the purposes of this License, Derivative Works +shall not include works that remain separable from, or merely link (or bind by +name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version +of the Work and any modifications or additions to that Work or Derivative Works +thereof, that is intentionally submitted to Licensor for inclusion in the Work +by the copyright owner or by an individual or Legal Entity authorized to submit +on behalf of the copyright owner. For the purposes of this definition, +"submitted" means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, and +issue tracking systems that are managed by, or on behalf of, the Licensor for +the purpose of discussing and improving the Work, but excluding communication +that is conspicuously marked or otherwise designated in writing by the copyright +owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf +of whom a Contribution has been received by Licensor and subsequently +incorporated within the Work. + +2. Grant of Copyright License. + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the Work and such +Derivative Works in Source or Object form. + +3. Grant of Patent License. + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable (except as stated in this section) patent license to make, have +made, use, offer to sell, sell, import, and otherwise transfer the Work, where +such license applies only to those patent claims licensable by such Contributor +that are necessarily infringed by their Contribution(s) alone or by combination +of their Contribution(s) with the Work to which such Contribution(s) was +submitted. If You institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work or a +Contribution incorporated within the Work constitutes direct or contributory +patent infringement, then any patent licenses granted to You under this License +for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. + +You may reproduce and distribute copies of the Work or Derivative Works thereof +in any medium, with or without modifications, and in Source or Object form, +provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of +this License; and +You must cause any modified files to carry prominent notices stating that You +changed the files; and +You must retain, in the Source form of any Derivative Works that You distribute, +all copyright, patent, trademark, and attribution notices from the Source form +of the Work, excluding those notices that do not pertain to any part of the +Derivative Works; and +If the Work includes a "NOTICE" text file as part of its distribution, then any +Derivative Works that You distribute must include a readable copy of the +attribution notices contained within such NOTICE file, excluding those notices +that do not pertain to any part of the Derivative Works, in at least one of the +following places: within a NOTICE text file distributed as part of the +Derivative Works; within the Source form or documentation, if provided along +with the Derivative Works; or, within a display generated by the Derivative +Works, if and wherever such third-party notices normally appear. The contents of +the NOTICE file are for informational purposes only and do not modify the +License. You may add Your own attribution notices within Derivative Works that +You distribute, alongside or as an addendum to the NOTICE text from the Work, +provided that such additional attribution notices cannot be construed as +modifying the License. +You may add Your own copyright statement to Your modifications and may provide +additional or different license terms and conditions for use, reproduction, or +distribution of Your modifications, or for any such Derivative Works as a whole, +provided Your use, reproduction, and distribution of the Work otherwise complies +with the conditions stated in this License. + +5. Submission of Contributions. + +Unless You explicitly state otherwise, any Contribution intentionally submitted +for inclusion in the Work by You to the Licensor shall be under the terms and +conditions of this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify the terms of +any separate license agreement you may have executed with Licensor regarding +such Contributions. + +6. Trademarks. + +This License does not grant permission to use the trade names, trademarks, +service marks, or product names of the Licensor, except as required for +reasonable and customary use in describing the origin of the Work and +reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. + +Unless required by applicable law or agreed to in writing, Licensor provides the +Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, +including, without limitation, any warranties or conditions of TITLE, +NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are +solely responsible for determining the appropriateness of using or +redistributing the Work and assume any risks associated with Your exercise of +permissions under this License. + +8. Limitation of Liability. + +In no event and under no legal theory, whether in tort (including negligence), +contract, or otherwise, unless required by applicable law (such as deliberate +and grossly negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, incidental, +or consequential damages of any character arising as a result of this License or +out of the use or inability to use the Work (including but not limited to +damages for loss of goodwill, work stoppage, computer failure or malfunction, or +any and all other commercial damages or losses), even if such Contributor has +been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. + +While redistributing the Work or Derivative Works thereof, You may choose to +offer, and charge a fee for, acceptance of support, warranty, indemnity, or +other liability obligations and/or rights consistent with this License. However, +in accepting such obligations, You may act only on Your own behalf and on Your +sole responsibility, not on behalf of any other Contributor, and only if You +agree to indemnify, defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason of your +accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work + +To apply the Apache License to your work, attach the following boilerplate +notice, with the fields enclosed by brackets "[]" replaced with your own +identifying information. (Don't include the brackets!) The text should be +enclosed in the appropriate comment syntax for the file format. We also +recommend that a file or class name and description of purpose be included on +the same "printed page" as the copyright notice for easier identification within +third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@img/sharp-linuxmusl-x64/README.md b/node_modules/@img/sharp-linuxmusl-x64/README.md new file mode 100644 index 0000000..f651f98 --- /dev/null +++ b/node_modules/@img/sharp-linuxmusl-x64/README.md @@ -0,0 +1,18 @@ +# `@img/sharp-linuxmusl-x64` + +Prebuilt sharp for use with Linux (musl) x64. + +## Licensing + +Copyright 2013 Lovell Fuller and others. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +[https://www.apache.org/licenses/LICENSE-2.0](https://www.apache.org/licenses/LICENSE-2.0) + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/node_modules/@img/sharp-linuxmusl-x64/index.cjs b/node_modules/@img/sharp-linuxmusl-x64/index.cjs new file mode 100644 index 0000000..6087bdf --- /dev/null +++ b/node_modules/@img/sharp-linuxmusl-x64/index.cjs @@ -0,0 +1,2 @@ +try { require.resolve('@img/sharp-libvips-linuxmusl-x64/binary'); } catch {} +module.exports = require('./lib/sharp-linuxmusl-x64-0.35.3.node'); \ No newline at end of file diff --git a/node_modules/@img/sharp-linuxmusl-x64/lib/sharp-linuxmusl-x64-0.35.3.node b/node_modules/@img/sharp-linuxmusl-x64/lib/sharp-linuxmusl-x64-0.35.3.node new file mode 100644 index 0000000..e40da07 Binary files /dev/null and b/node_modules/@img/sharp-linuxmusl-x64/lib/sharp-linuxmusl-x64-0.35.3.node differ diff --git a/node_modules/@img/sharp-linuxmusl-x64/package.json b/node_modules/@img/sharp-linuxmusl-x64/package.json new file mode 100644 index 0000000..1b159e5 --- /dev/null +++ b/node_modules/@img/sharp-linuxmusl-x64/package.json @@ -0,0 +1,47 @@ +{ + "name": "@img/sharp-linuxmusl-x64", + "version": "0.35.3", + "description": "Prebuilt sharp for use with Linux (musl) x64", + "author": "Lovell Fuller ", + "homepage": "https://sharp.pixelplumbing.com", + "repository": { + "type": "git", + "url": "git+https://github.com/lovell/sharp.git", + "directory": "npm/linuxmusl-x64" + }, + "license": "Apache-2.0", + "funding": { + "url": "https://opencollective.com/libvips" + }, + "preferUnplugged": true, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.3.2" + }, + "files": [ + "index.cjs", + "lib" + ], + "publishConfig": { + "access": "public" + }, + "type": "commonjs", + "exports": { + "./sharp.node": "./index.cjs", + "./package": "./package.json" + }, + "engines": { + "node": ">=20.9.0" + }, + "config": { + "musl": ">=1.2.5" + }, + "os": [ + "linux" + ], + "libc": [ + "musl" + ], + "cpu": [ + "x64" + ] +} diff --git a/node_modules/@img/sharp-wasm32/LICENSE b/node_modules/@img/sharp-wasm32/LICENSE new file mode 100644 index 0000000..37ec93a --- /dev/null +++ b/node_modules/@img/sharp-wasm32/LICENSE @@ -0,0 +1,191 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and +distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright +owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities +that control, are controlled by, or are under common control with that entity. +For the purposes of this definition, "control" means (i) the power, direct or +indirect, to cause the direction or management of such entity, whether by +contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the +outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising +permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including +but not limited to software source code, documentation source, and configuration +files. + +"Object" form shall mean any form resulting from mechanical transformation or +translation of a Source form, including but not limited to compiled object code, +generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made +available under the License, as indicated by a copyright notice that is included +in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that +is based on (or derived from) the Work and for which the editorial revisions, +annotations, elaborations, or other modifications represent, as a whole, an +original work of authorship. For the purposes of this License, Derivative Works +shall not include works that remain separable from, or merely link (or bind by +name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version +of the Work and any modifications or additions to that Work or Derivative Works +thereof, that is intentionally submitted to Licensor for inclusion in the Work +by the copyright owner or by an individual or Legal Entity authorized to submit +on behalf of the copyright owner. For the purposes of this definition, +"submitted" means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, and +issue tracking systems that are managed by, or on behalf of, the Licensor for +the purpose of discussing and improving the Work, but excluding communication +that is conspicuously marked or otherwise designated in writing by the copyright +owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf +of whom a Contribution has been received by Licensor and subsequently +incorporated within the Work. + +2. Grant of Copyright License. + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the Work and such +Derivative Works in Source or Object form. + +3. Grant of Patent License. + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable (except as stated in this section) patent license to make, have +made, use, offer to sell, sell, import, and otherwise transfer the Work, where +such license applies only to those patent claims licensable by such Contributor +that are necessarily infringed by their Contribution(s) alone or by combination +of their Contribution(s) with the Work to which such Contribution(s) was +submitted. If You institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work or a +Contribution incorporated within the Work constitutes direct or contributory +patent infringement, then any patent licenses granted to You under this License +for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. + +You may reproduce and distribute copies of the Work or Derivative Works thereof +in any medium, with or without modifications, and in Source or Object form, +provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of +this License; and +You must cause any modified files to carry prominent notices stating that You +changed the files; and +You must retain, in the Source form of any Derivative Works that You distribute, +all copyright, patent, trademark, and attribution notices from the Source form +of the Work, excluding those notices that do not pertain to any part of the +Derivative Works; and +If the Work includes a "NOTICE" text file as part of its distribution, then any +Derivative Works that You distribute must include a readable copy of the +attribution notices contained within such NOTICE file, excluding those notices +that do not pertain to any part of the Derivative Works, in at least one of the +following places: within a NOTICE text file distributed as part of the +Derivative Works; within the Source form or documentation, if provided along +with the Derivative Works; or, within a display generated by the Derivative +Works, if and wherever such third-party notices normally appear. The contents of +the NOTICE file are for informational purposes only and do not modify the +License. You may add Your own attribution notices within Derivative Works that +You distribute, alongside or as an addendum to the NOTICE text from the Work, +provided that such additional attribution notices cannot be construed as +modifying the License. +You may add Your own copyright statement to Your modifications and may provide +additional or different license terms and conditions for use, reproduction, or +distribution of Your modifications, or for any such Derivative Works as a whole, +provided Your use, reproduction, and distribution of the Work otherwise complies +with the conditions stated in this License. + +5. Submission of Contributions. + +Unless You explicitly state otherwise, any Contribution intentionally submitted +for inclusion in the Work by You to the Licensor shall be under the terms and +conditions of this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify the terms of +any separate license agreement you may have executed with Licensor regarding +such Contributions. + +6. Trademarks. + +This License does not grant permission to use the trade names, trademarks, +service marks, or product names of the Licensor, except as required for +reasonable and customary use in describing the origin of the Work and +reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. + +Unless required by applicable law or agreed to in writing, Licensor provides the +Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, +including, without limitation, any warranties or conditions of TITLE, +NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are +solely responsible for determining the appropriateness of using or +redistributing the Work and assume any risks associated with Your exercise of +permissions under this License. + +8. Limitation of Liability. + +In no event and under no legal theory, whether in tort (including negligence), +contract, or otherwise, unless required by applicable law (such as deliberate +and grossly negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, incidental, +or consequential damages of any character arising as a result of this License or +out of the use or inability to use the Work (including but not limited to +damages for loss of goodwill, work stoppage, computer failure or malfunction, or +any and all other commercial damages or losses), even if such Contributor has +been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. + +While redistributing the Work or Derivative Works thereof, You may choose to +offer, and charge a fee for, acceptance of support, warranty, indemnity, or +other liability obligations and/or rights consistent with this License. However, +in accepting such obligations, You may act only on Your own behalf and on Your +sole responsibility, not on behalf of any other Contributor, and only if You +agree to indemnify, defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason of your +accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work + +To apply the Apache License to your work, attach the following boilerplate +notice, with the fields enclosed by brackets "[]" replaced with your own +identifying information. (Don't include the brackets!) The text should be +enclosed in the appropriate comment syntax for the file format. We also +recommend that a file or class name and description of purpose be included on +the same "printed page" as the copyright notice for easier identification within +third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@img/sharp-wasm32/README.md b/node_modules/@img/sharp-wasm32/README.md new file mode 100644 index 0000000..876651e --- /dev/null +++ b/node_modules/@img/sharp-wasm32/README.md @@ -0,0 +1,50 @@ +# `@img/sharp-wasm32` + +Prebuilt sharp for use with WebAssembly. + +## Licensing + +Copyright 2013 Lovell Fuller and others. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +[https://www.apache.org/licenses/LICENSE-2.0](https://www.apache.org/licenses/LICENSE-2.0) + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +This software contains third-party libraries +used under the terms of the following licenses: + +| Library | Used under the terms of | +|---------------|----------------------------------------------------------------------------------------------------------| +| aom | BSD 2-Clause + [Alliance for Open Media Patent License 1.0](https://aomedia.org/license/patent-license/) | +| cgif | MIT License | +| emscripten | [MIT License](https://github.com/emscripten-core/emscripten/blob/main/LICENSE) | +| expat | MIT License | +| glib | LGPLv3 | +| highway | BSD 3-Clause | +| lcms | MIT License | +| libexif | LGPLv3 | +| libffi | MIT License | +| libheif | LGPLv3 | +| libimagequant | [BSD 2-Clause](https://github.com/lovell/libimagequant/blob/main/COPYRIGHT) | +| libnsgif | MIT License | +| libpng | [libpng License](https://github.com/pnggroup/libpng/blob/master/LICENSE) | +| libtiff | [libtiff License](https://gitlab.com/libtiff/libtiff/blob/master/LICENSE.md) (BSD-like) | +| libultrahdr | MIT License | +| libvips | LGPLv3 | +| libwebp | New BSD License | +| mozjpeg | [zlib License, IJG License, BSD 3-Clause](https://github.com/mozilla/mozjpeg/blob/master/LICENSE.md) | +| resvg | MIT License | +| zlib-ng | [zlib License](https://github.com/zlib-ng/zlib-ng/blob/develop/LICENSE.md) | + +Use of libraries under the terms of the LGPLv3 is via the +"any later version" clause of the LGPLv2 or LGPLv2.1. + +Please report any errors or omissions via +https://github.com/lovell/sharp-libvips/issues/new diff --git a/node_modules/@img/sharp-wasm32/index.cjs b/node_modules/@img/sharp-wasm32/index.cjs new file mode 100644 index 0000000..e4dc722 --- /dev/null +++ b/node_modules/@img/sharp-wasm32/index.cjs @@ -0,0 +1 @@ +module.exports = require('./lib/sharp-wasm32-0.35.3.node'); \ No newline at end of file diff --git a/node_modules/@img/sharp-wasm32/lib/sharp-wasm32-0.35.3.node.js b/node_modules/@img/sharp-wasm32/lib/sharp-wasm32-0.35.3.node.js new file mode 100644 index 0000000..e645363 --- /dev/null +++ b/node_modules/@img/sharp-wasm32/lib/sharp-wasm32-0.35.3.node.js @@ -0,0 +1 @@ +var Module=typeof Module!="undefined"?Module:{};var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";var ENVIRONMENT_IS_PTHREAD=ENVIRONMENT_IS_WORKER&&globalThis.name=="em-pthread";if(ENVIRONMENT_IS_NODE){var worker_threads=require("node:worker_threads");globalThis.Worker=worker_threads.Worker;ENVIRONMENT_IS_WORKER=!worker_threads.isMainThread;ENVIRONMENT_IS_PTHREAD=ENVIRONMENT_IS_WORKER&&worker_threads.workerData=="em-pthread"}Module.preRun=()=>{ENV.VIPS_CONCURRENCY=Number(process.env.VIPS_CONCURRENCY)||1};Module.onRuntimeInitialized=()=>{module.exports=Module.emnapiInit({context:require("@emnapi/runtime").getDefaultContext()});process.once("exit",()=>{_vips_shutdown();_uv_library_shutdown()})};var programArgs=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName;if(typeof __filename!="undefined"){_scriptName=__filename}else if(ENVIRONMENT_IS_WORKER){_scriptName=self.location.href}var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");scriptDirectory=__dirname+"/";readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}programArgs=process.argv.slice(2);if(typeof module!="undefined"){module["exports"]=Module}quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}if(!ENVIRONMENT_IS_NODE){if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var defaultPrint=console.log.bind(console);var defaultPrintErr=console.error.bind(console);if(ENVIRONMENT_IS_NODE){var utils=require("node:util");var stringify=a=>typeof a=="object"?utils.inspect(a):a;defaultPrint=(...args)=>fs.writeSync(1,args.map(stringify).join(" ")+"\n");defaultPrintErr=(...args)=>fs.writeSync(2,args.map(stringify).join(" ")+"\n")}var out=defaultPrint;var err=defaultPrintErr;var wasmBinary;var wasmModule;var ABORT=false;var EXITSTATUS;var isFileURI=filename=>filename.startsWith("file://");function growMemViews(){if(wasmMemory.buffer!=HEAP8.buffer){updateMemoryViews()}}if(ENVIRONMENT_IS_NODE&&ENVIRONMENT_IS_PTHREAD){globalThis.self=globalThis;var parentPort=worker_threads.parentPort;if(!globalThis.postMessage){parentPort.on("message",msg=>globalThis.onmessage?.({data:msg}));globalThis.postMessage=msg=>parentPort.postMessage(msg)}process.on("uncaughtException",err=>{postMessage({cmd:8,error:err});process.exit(1)})}var startWorker;if(ENVIRONMENT_IS_PTHREAD){var initializedJS=false;self.onunhandledrejection=e=>{throw e.reason||e};function handleMessage(e){try{var msgData=e.data;var cmd=msgData.cmd;if(cmd==1){let messageQueue=[];self.onmessage=e=>messageQueue.push(e);startWorker=()=>{postMessage({cmd:3});for(let msg of messageQueue){handleMessage(msg)}self.onmessage=handleMessage};for(const handler of msgData.handlers){if(!Module[handler]||Module[handler].proxy){Module[handler]=(...args)=>{postMessage({cmd:9,handler,args})};if(handler=="print")out=Module[handler];if(handler=="printErr")err=Module[handler]}}wasmMemory=msgData.wasmMemory;updateMemoryViews();wasmModule=msgData.wasmModule;createWasm();run()}else if(cmd==2){establishStackSpace(msgData.pthread_ptr);__emscripten_thread_init(msgData.pthread_ptr,0,0,1,0,0);PThread.threadInitTLS();__emscripten_thread_mailbox_await(msgData.pthread_ptr);if(!initializedJS){initializedJS=true}try{invokeEntryPoint(msgData.start_routine,msgData.arg)}catch(ex){if(ex!="unwind"){throw ex}}}else if(cmd==4){if(initializedJS){checkMailbox()}}else if(cmd){err(`worker: received unknown command ${cmd}`);err(msgData)}}catch(ex){if(runtimeInitialized)__emscripten_thread_crashed();throw ex}}self.onmessage=handleMessage}var runtimeInitialized=false;function updateMemoryViews(){var b=wasmMemory.buffer;HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);HEAPU8=new Uint8Array(b);HEAPU16=new Uint16Array(b);HEAP32=new Int32Array(b);HEAPU32=new Uint32Array(b);HEAPF32=new Float32Array(b);HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b);HEAPU64=new BigUint64Array(b)}function initMemory(){if(ENVIRONMENT_IS_PTHREAD){return}if(Module["wasmMemory"]){wasmMemory=Module["wasmMemory"]}else{var INITIAL_MEMORY=Module["INITIAL_MEMORY"]||16777216;wasmMemory=new WebAssembly.Memory({initial:INITIAL_MEMORY/65536,maximum:32768,shared:true})}updateMemoryViews()}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;if(ENVIRONMENT_IS_PTHREAD)return startWorker();if(!Module["noFSInit"]&&!FS.initialized)FS.init();TTY.init();wasmExports["ib"]();FS.ignorePermissions=false}function postRun(){if(ENVIRONMENT_IS_PTHREAD){return}if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what=`Aborted(${what})`;err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";if(runtimeInitialized){___trap()}var e=new WebAssembly.RuntimeError(what);throw e}var wasmBinaryFile;function findWasmBinary(){return locateFile("sharp-wasm32-0.35.3.node.wasm")}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw'sync fetching of the wasm failed: you can preload it to Module["wasmBinary"] manually, or emcc.py will do that for you when generating HTML (but not JS)'}function instantiateSync(file,info){var module;var binary=getBinarySync(file);module=new WebAssembly.Module(binary);var instance=new WebAssembly.Instance(module,info);return[instance,module]}function getWasmImports(){assignWasmImports();var imports={a:wasmImports};return imports}function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;registerTLSInit(wasmExports["rb"]);assignWasmExports(wasmExports);wasmModule=module;return wasmExports}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(inst,mod)=>{resolve(receiveInstance(inst,mod))})})}if(ENVIRONMENT_IS_PTHREAD){var instance=new WebAssembly.Instance(wasmModule,getWasmImports());return receiveInstance(instance,wasmModule)}wasmBinaryFile??=findWasmBinary();var result=instantiateSync(wasmBinaryFile,info);return receiveInstance(result[0],result[1])}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var HEAP16;var HEAP32;var HEAP64;var HEAP8;var HEAPF32;var HEAPF64;var HEAPU16;var HEAPU32;var HEAPU64;var HEAPU8;var terminateWorker=worker=>{worker.terminate();worker.onmessage=e=>{}};var cleanupThread=pthread_ptr=>{var worker=PThread.pthreads[pthread_ptr];PThread.returnWorkerToPool(worker)};var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPreRuns=[];var addOnPreRun=cb=>onPreRuns.push(cb);var spawnThread=threadParams=>{var worker=PThread.getNewWorker();if(!worker){return 6}PThread.pthreads[threadParams.pthread_ptr]=worker;worker.pthread_ptr=threadParams.pthread_ptr;var msg={cmd:2,start_routine:threadParams.startRoutine,arg:threadParams.arg,pthread_ptr:threadParams.pthread_ptr};worker.postMessage(msg,threadParams.transferList);return 0};var runtimeKeepaliveCounter=0;var keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0;var stackSave=()=>_emscripten_stack_get_current();var stackRestore=val=>__emscripten_stack_restore(val);var stackAlloc=sz=>__emscripten_stack_alloc(sz);var proxyToMainThread=(funcIndex,emAsmAddr,proxyMode,...callArgs)=>{var bufSize=8*callArgs.length*2;var sp=stackSave();var args=stackAlloc(bufSize);var b=args>>3;for(var arg of callArgs){if(typeof arg=="bigint"){(growMemViews(),HEAP64)[b++]=1n;(growMemViews(),HEAP64)[b++]=arg}else{(growMemViews(),HEAP64)[b++]=0n;(growMemViews(),HEAPF64)[b++]=arg}}var rtn=__emscripten_run_js_on_main_thread(funcIndex,emAsmAddr,bufSize,args,proxyMode);stackRestore(sp);return rtn};function _proc_exit(code){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(0,0,1,code);EXITSTATUS=code;if(!keepRuntimeAlive()){PThread.terminateAllThreads();Module["onExit"]?.(code);ABORT=true}quit_(code,new ExitStatus(code))}function exitOnMainThread(returnCode){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(1,0,0,returnCode);_exit(returnCode)}var exitJS=(status,implicit)=>{EXITSTATUS=status;if(ENVIRONMENT_IS_PTHREAD){exitOnMainThread(status);throw"unwind"}_proc_exit(status)};var _exit=exitJS;var waitAsyncPolyfilled=!Atomics.waitAsync||globalThis.navigator?.userAgent&&Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2])<91;var PThread={unusedWorkers:[],tlsInitFunctions:[],pthreads:{},init(){if(!ENVIRONMENT_IS_PTHREAD){PThread.initMainThread()}},initMainThread(){},terminateAllThreads:()=>{for(var worker of Object.values(PThread.pthreads)){terminateWorker(worker)}for(var worker of PThread.unusedWorkers){terminateWorker(worker)}PThread.unusedWorkers=[];PThread.pthreads={}},terminateRuntime:()=>{PThread.terminateAllThreads();var pthread_ptr=_pthread_self();___set_thread_state(0,0,0,1);if(!waitAsyncPolyfilled){Atomics.notify((growMemViews(),HEAP32),pthread_ptr>>2)}},returnWorkerToPool:worker=>{var pthread_ptr=worker.pthread_ptr;delete PThread.pthreads[pthread_ptr];PThread.unusedWorkers.push(worker);worker.pthread_ptr=0;__emscripten_thread_free_data(pthread_ptr)},threadInitTLS(){PThread.tlsInitFunctions.forEach(f=>f())},loadWasmModuleToWorker:worker=>new Promise(onFinishedLoading=>{worker.onmessage=e=>{var d=e.data;var cmd=d.cmd;if(d.targetThread){var targetWorker=PThread.pthreads[d.targetThread];targetWorker?.postMessage(d);return}if(d==="setimmediate"||d==="_si"){worker.postMessage(d);return}switch(cmd){case 4:checkMailbox();break;case 5:spawnThread(d);break;case 6:callUserCallback(()=>cleanupThread(d.thread));break;case 3:if(ENVIRONMENT_IS_NODE&&!worker.strongref){worker.unref()}onFinishedLoading(worker);break;case 8:worker.onerror(d.error);break;case 9:Module[d.handler](...d.args);break;default:if(cmd)err(`worker sent an unknown command ${cmd}`)}};worker.onerror=e=>{var message="worker sent an error!";err(`${message} ${e.filename}:${e.lineno}: ${e.message}`);throw e};if(ENVIRONMENT_IS_NODE){worker.on("message",data=>worker.onmessage({data}));worker.on("error",e=>worker.onerror(e))}var handlers=[];var knownHandlers=["onExit","onAbort","print","printErr"];for(var handler of knownHandlers){if(Module.propertyIsEnumerable(handler)){handlers.push(handler)}}worker.postMessage({cmd:1,handlers,wasmMemory,wasmModule})}),allocateUnusedWorker(){var worker;var pthreadMainJs=_scriptName;if(Module["mainScriptUrlOrBlob"]){pthreadMainJs=Module["mainScriptUrlOrBlob"];if(typeof pthreadMainJs!="string"){pthreadMainJs=URL.createObjectURL(pthreadMainJs)}}worker=new Worker(pthreadMainJs,{workerData:"em-pthread",name:"em-pthread"});PThread.unusedWorkers.push(worker);return worker},getNewWorker(){if(PThread.unusedWorkers.length==0){var newWorker=PThread.allocateUnusedWorker();PThread.loadWasmModuleToWorker(newWorker)}return PThread.unusedWorkers.pop()}};var onPostRuns=[];var addOnPostRun=cb=>onPostRuns.push(cb);function establishStackSpace(pthread_ptr){var stackHigh=(growMemViews(),HEAPU32)[pthread_ptr+48>>2];var stackSize=(growMemViews(),HEAPU32)[pthread_ptr+52>>2];var stackLow=stackHigh-stackSize;_emscripten_stack_set_limits(stackHigh,stackLow);stackRestore(stackHigh)}var getWasmTableEntry=funcPtr=>wasmTable.get(funcPtr);var invokeEntryPoint=(ptr,arg)=>{runtimeKeepaliveCounter=0;noExitRuntime=0;var result=getWasmTableEntry(ptr)(arg);function finish(result){if(keepRuntimeAlive()){EXITSTATUS=result;return}__emscripten_thread_exit(result)}finish(result)};var noExitRuntime=true;var registerTLSInit=tlsInitFunc=>PThread.tlsInitFunctions.push(tlsInitFunc);var wasmMemory;var UTF8Decoder=new TextDecoder;var findStringEnd=(heapOrArray,idx,maxBytesToRead,ignoreNul)=>{var maxIdx=idx+maxBytesToRead;if(ignoreNul)return maxIdx;while(heapOrArray[idx]&&!(idx>=maxIdx))++idx;return idx};var UTF8ToString=(ptr,maxBytesToRead,ignoreNul)=>{if(!ptr)return"";var end=findStringEnd((growMemViews(),HEAPU8),ptr,maxBytesToRead,ignoreNul);return UTF8Decoder.decode((growMemViews(),HEAPU8).slice(ptr,end))};var ___assert_fail=(condition,filename,line,func)=>abort(`Assertion failed: ${UTF8ToString(condition)}, at: `+[filename?UTF8ToString(filename):"unknown filename",line,func?UTF8ToString(func):"unknown function"]);var ___call_sighandler=(fp,sig)=>getWasmTableEntry(fp)(sig);function pthreadCreateProxied(pthread_ptr,attr,startRoutine,arg){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(2,0,1,pthread_ptr,attr,startRoutine,arg);return ___pthread_create_js(pthread_ptr,attr,startRoutine,arg)}var _emscripten_has_threading_support=()=>!!globalThis.SharedArrayBuffer;var ___pthread_create_js=(pthread_ptr,attr,startRoutine,arg)=>{if(!_emscripten_has_threading_support()){return 6}var transferList=[];var error=0;if(ENVIRONMENT_IS_PTHREAD&&(transferList.length===0||error)){return pthreadCreateProxied(pthread_ptr,attr,startRoutine,arg)}if(error)return error;var threadParams={startRoutine,pthread_ptr,arg,transferList};if(ENVIRONMENT_IS_PTHREAD){threadParams.cmd=5;postMessage(threadParams,transferList);return 0}return spawnThread(threadParams)};var nodePath=require("node:path");var PATH={isAbs:nodePath.isAbsolute,normalize:nodePath.normalize,dirname:nodePath.dirname,basename:nodePath.basename,join:nodePath.join,join2:nodePath.join};var initRandomFill=()=>{if(ENVIRONMENT_IS_NODE){var nodeCrypto=require("node:crypto");return view=>(nodeCrypto.randomFillSync(view),0)}return view=>(view.set(crypto.getRandomValues(new Uint8Array(view.byteLength))),0)};var randomFill=view=>(randomFill=initRandomFill())(view);var PATH_FS={resolve:(...paths)=>{paths.unshift(FS.cwd());return nodePath.posix.resolve(...paths)},relative:(from,to)=>nodePath.posix.relative(from||FS.cwd(),to||FS.cwd())};var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead,ignoreNul)=>{var endPtr=findStringEnd(heapOrArray,idx,maxBytesToRead,ignoreNul);return UTF8Decoder.decode(heapOrArray.buffer?heapOrArray.slice(idx,endPtr):new Uint8Array(heapOrArray.slice(idx,endPtr)))};var FS_stdin_getChar_buffer=[];var lengthBytesUTF8=str=>{var len=0;for(var i=0;i=55296&&c<=57343){len+=4;++i}else{len+=3}}return len};var stringToUTF8Array=(str,heap,outIdx,maxBytesToWrite)=>{if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63;i++}}heap[outIdx]=0;return outIdx-startIdx};var intArrayFromString=(stringy,dontAddNull,length)=>{var len=length>0?length:lengthBytesUTF8(stringy)+1;var u8array=new Array(len);var numBytesWritten=stringToUTF8Array(stringy,u8array,0,u8array.length);if(dontAddNull)u8array.length=numBytesWritten;return u8array};var FS_stdin_getChar=()=>{if(!FS_stdin_getChar_buffer.length){var result=null;if(ENVIRONMENT_IS_NODE){var BUFSIZE=256;var buf=Buffer.alloc(BUFSIZE);var bytesRead=0;var fd=process.stdin.fd;try{bytesRead=fs.readSync(fd,buf,0,BUFSIZE)}catch(e){if(e.toString().includes("EOF"))bytesRead=0;else throw e}if(bytesRead>0){result=buf.slice(0,bytesRead).toString("utf-8")}}else{}if(!result){return null}FS_stdin_getChar_buffer=intArrayFromString(result,true)}return FS_stdin_getChar_buffer.shift()};var TTY={ttys:[],init(){},shutdown(){},register(dev,ops){TTY.ttys[dev]={input:[],output:[],ops};FS.registerDevice(dev,TTY.stream_ops)},stream_ops:{open(stream){var tty=TTY.ttys[stream.node.rdev];if(!tty){throw new FS.ErrnoError(43)}stream.tty=tty;stream.seekable=false},close(stream){stream.tty.ops.fsync(stream.tty)},fsync(stream){stream.tty.ops.fsync(stream.tty)},read(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.get_char){throw new FS.ErrnoError(60)}var bytesRead=0;for(var i=0;i0){out(UTF8ArrayToString(tty.output));tty.output=[]}},ioctl_tcgets(tty){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets(tty,optional_actions,data){return 0},ioctl_tiocgwinsz(tty){return[24,80]}},default_tty1_ops:{put_char(tty,val){if(val===null||val===10){err(UTF8ArrayToString(tty.output));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output?.length>0){err(UTF8ArrayToString(tty.output));tty.output=[]}}}};var zeroMemory=(ptr,size)=>(growMemViews(),HEAPU8).fill(0,ptr,ptr+size);var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var mmapAlloc=size=>{size=alignMemory(size,65536);var ptr=_emscripten_builtin_memalign(65536,size);if(ptr)zeroMemory(ptr,size);return ptr};var MEMFS={ops_table:null,mount(mount){return MEMFS.createNode(null,"/",16895,0)},createNode(parent,name,mode,dev){if(FS.isBlkdev(mode)||FS.isFIFO(mode)){throw new FS.ErrnoError(63)}MEMFS.ops_table||={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}};var node=FS.createNode(parent,name,mode,dev);if(FS.isDir(node.mode)){node.node_ops=MEMFS.ops_table.dir.node;node.stream_ops=MEMFS.ops_table.dir.stream;node.contents={}}else if(FS.isFile(node.mode)){node.node_ops=MEMFS.ops_table.file.node;node.stream_ops=MEMFS.ops_table.file.stream;node.usedBytes=0;node.contents=MEMFS.emptyFileContents??=new Uint8Array(0)}else if(FS.isLink(node.mode)){node.node_ops=MEMFS.ops_table.link.node;node.stream_ops=MEMFS.ops_table.link.stream}else if(FS.isChrdev(node.mode)){node.node_ops=MEMFS.ops_table.chrdev.node;node.stream_ops=MEMFS.ops_table.chrdev.stream}node.atime=node.mtime=node.ctime=Date.now();if(parent){parent.contents[name]=node;parent.atime=parent.mtime=parent.ctime=node.atime}return node},getFileDataAsTypedArray(node){return node.contents.subarray(0,node.usedBytes)},expandFileStorage(node,newCapacity){var prevCapacity=node.contents.length;if(prevCapacity>=newCapacity)return;var CAPACITY_DOUBLING_MAX=1024*1024;newCapacity=Math.max(newCapacity,prevCapacity*(prevCapacity>>0);if(prevCapacity)newCapacity=Math.max(newCapacity,256);var oldContents=MEMFS.getFileDataAsTypedArray(node);node.contents=new Uint8Array(newCapacity);node.contents.set(oldContents)},resizeFileStorage(node,newSize){if(node.usedBytes==newSize)return;var oldContents=node.contents;node.contents=new Uint8Array(newSize);node.contents.set(oldContents.subarray(0,Math.min(newSize,node.usedBytes)));node.usedBytes=newSize},node_ops:{getattr(node){var attr={};attr.dev=FS.isChrdev(node.mode)?node.id:1;attr.ino=node.id;attr.mode=node.mode;attr.nlink=1;attr.uid=0;attr.gid=0;attr.rdev=node.rdev;if(FS.isDir(node.mode)){attr.size=4096}else if(FS.isFile(node.mode)){attr.size=node.usedBytes}else if(FS.isLink(node.mode)){attr.size=node.link.length}else{attr.size=0}attr.atime=new Date(node.atime);attr.mtime=new Date(node.mtime);attr.ctime=new Date(node.ctime);attr.blksize=4096;attr.blocks=Math.ceil(attr.size/attr.blksize);return attr},setattr(node,attr){for(const key of["mode","atime","mtime","ctime"]){if(attr[key]!=null){node[key]=attr[key]}}if(attr.size!==undefined){MEMFS.resizeFileStorage(node,attr.size)}},lookup(parent,name){if(!MEMFS.doesNotExistError){MEMFS.doesNotExistError=new FS.ErrnoError(44);MEMFS.doesNotExistError.stack=""}throw MEMFS.doesNotExistError},mknod(parent,name,mode,dev){return MEMFS.createNode(parent,name,mode,dev)},rename(old_node,new_dir,new_name){var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(new_node){if(FS.isDir(old_node.mode)){for(var i in new_node.contents){throw new FS.ErrnoError(55)}}FS.hashRemoveNode(new_node)}delete old_node.parent.contents[old_node.name];new_dir.contents[new_name]=old_node;old_node.name=new_name;new_dir.ctime=new_dir.mtime=old_node.parent.ctime=old_node.parent.mtime=Date.now()},unlink(parent,name){delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},rmdir(parent,name){var node=FS.lookupNode(parent,name);for(var i in node.contents){throw new FS.ErrnoError(55)}delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},readdir(node){return[".","..",...Object.keys(node.contents)]},symlink(parent,newname,oldpath){var node=MEMFS.createNode(parent,newname,511|40960,0);node.link=oldpath;return node},readlink(node){if(!FS.isLink(node.mode)){throw new FS.ErrnoError(28)}return node.link}},stream_ops:{read(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=stream.node.usedBytes)return 0;var size=Math.min(stream.node.usedBytes-position,length);buffer.set(contents.subarray(position,position+size),offset);return size},write(stream,buffer,offset,length,position,canOwn){if(buffer.buffer===(growMemViews(),HEAP8).buffer){canOwn=false}if(!length)return 0;var node=stream.node;node.mtime=node.ctime=Date.now();if(canOwn){node.contents=buffer.subarray(offset,offset+length);node.usedBytes=length}else if(node.usedBytes===0&&position===0){node.contents=buffer.slice(offset,offset+length);node.usedBytes=length}else{MEMFS.expandFileStorage(node,position+length);node.contents.set(buffer.subarray(offset,offset+length),position);node.usedBytes=Math.max(node.usedBytes,position+length)}return length},llseek(stream,offset,whence){var position=offset;if(whence===1){position+=stream.position}else if(whence===2){if(FS.isFile(stream.node.mode)){position+=stream.node.usedBytes}}if(position<0){throw new FS.ErrnoError(28)}return position},mmap(stream,length,position,prot,flags){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}var ptr;var allocated;var contents=stream.node.contents;if(!(flags&2)&&contents.buffer===(growMemViews(),HEAP8).buffer){allocated=false;ptr=contents.byteOffset}else{allocated=true;ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}if(contents){if(position>0||position+length{if(typeof str!="string")return str;var flagModes={r:0,"r+":2,w:512|64|1,"w+":512|64|2,a:1024|64|1,"a+":1024|64|2};var flags=flagModes[str];if(typeof flags=="undefined"){throw new Error(`Unknown file open mode: ${str}`)}return flags};var FS_fileDataToTypedArray=data=>{if(typeof data=="string"){data=intArrayFromString(data,true)}if(!data.subarray){data=new Uint8Array(data)}return data};var FS_getMode=(canRead,canWrite)=>{var mode=0;if(canRead)mode|=292|73;if(canWrite)mode|=146;return mode};var ERRNO_CODES={EPERM:63,ENOENT:44,ESRCH:71,EINTR:27,EIO:29,ENXIO:60,E2BIG:1,ENOEXEC:45,EBADF:8,ECHILD:12,EAGAIN:6,EWOULDBLOCK:6,ENOMEM:48,EACCES:2,EFAULT:21,ENOTBLK:105,EBUSY:10,EEXIST:20,EXDEV:75,ENODEV:43,ENOTDIR:54,EISDIR:31,EINVAL:28,ENFILE:41,EMFILE:33,ENOTTY:59,ETXTBSY:74,EFBIG:22,ENOSPC:51,ESPIPE:70,EROFS:69,EMLINK:34,EPIPE:64,EDOM:18,ERANGE:68,ENOMSG:49,EIDRM:24,ECHRNG:106,EL2NSYNC:156,EL3HLT:107,EL3RST:108,ELNRNG:109,EUNATCH:110,ENOCSI:111,EL2HLT:112,EDEADLK:16,ENOLCK:46,EBADE:113,EBADR:114,EXFULL:115,ENOANO:104,EBADRQC:103,EBADSLT:102,EDEADLOCK:16,EBFONT:101,ENOSTR:100,ENODATA:116,ETIME:117,ENOSR:118,ENONET:119,ENOPKG:120,EREMOTE:121,ENOLINK:47,EADV:122,ESRMNT:123,ECOMM:124,EPROTO:65,EMULTIHOP:36,EDOTDOT:125,EBADMSG:9,ENOTUNIQ:126,EBADFD:127,EREMCHG:128,ELIBACC:129,ELIBBAD:130,ELIBSCN:131,ELIBMAX:132,ELIBEXEC:133,ENOSYS:52,ENOTEMPTY:55,ENAMETOOLONG:37,ELOOP:32,EOPNOTSUPP:138,EPFNOSUPPORT:139,ECONNRESET:15,ENOBUFS:42,EAFNOSUPPORT:5,EPROTOTYPE:67,ENOTSOCK:57,ENOPROTOOPT:50,ESHUTDOWN:140,ECONNREFUSED:14,EADDRINUSE:3,ECONNABORTED:13,ENETUNREACH:40,ENETDOWN:38,ETIMEDOUT:73,EHOSTDOWN:142,EHOSTUNREACH:23,EINPROGRESS:26,EALREADY:7,EDESTADDRREQ:17,EMSGSIZE:35,EPROTONOSUPPORT:66,ESOCKTNOSUPPORT:137,EADDRNOTAVAIL:4,ENETRESET:39,EISCONN:30,ENOTCONN:53,ETOOMANYREFS:141,EUSERS:136,EDQUOT:19,ESTALE:72,ENOTSUP:138,ENOMEDIUM:148,EILSEQ:25,EOVERFLOW:61,ECANCELED:11,ENOTRECOVERABLE:56,EOWNERDEAD:62,ESTRPIPE:135};var NODEFS={isWindows:false,staticInit(){NODEFS.isWindows=!!process.platform.match(/^win/);var flags=process.binding("constants")["fs"];NODEFS.flagsForNodeMap={1024:flags["O_APPEND"],64:flags["O_CREAT"],128:flags["O_EXCL"],256:flags["O_NOCTTY"],0:flags["O_RDONLY"],2:flags["O_RDWR"],4096:flags["O_SYNC"],512:flags["O_TRUNC"],1:flags["O_WRONLY"],131072:flags["O_NOFOLLOW"]}},convertNodeCode(e){var code=e.code;return ERRNO_CODES[code]},tryFSOperation(f){try{return f()}catch(e){if(!e.code)throw e;if(e.code==="UNKNOWN")throw new FS.ErrnoError(28);throw new FS.ErrnoError(NODEFS.convertNodeCode(e))}},mount(mount){return NODEFS.createNode(null,"/",NODEFS.getMode(mount.opts.root),0)},createNode(parent,name,mode,dev){if(!FS.isDir(mode)&&!FS.isFile(mode)&&!FS.isLink(mode)){throw new FS.ErrnoError(28)}var node=FS.createNode(parent,name,mode);node.node_ops=NODEFS.node_ops;node.stream_ops=NODEFS.stream_ops;return node},getMode(path){return NODEFS.tryFSOperation(()=>{var mode=fs.lstatSync(path).mode;if(NODEFS.isWindows){mode|=(mode&292)>>2}return mode})},realPath(node){var parts=[];while(node.parent!==node){parts.push(node.name);node=node.parent}parts.push(node.mount.opts.root);parts.reverse();return PATH.join(...parts)},flagsForNode(flags){flags&=~2097152;flags&=~2048;flags&=~32768;flags&=~524288;flags&=~65536;var newFlags=0;for(var k in NODEFS.flagsForNodeMap){if(flags&k){newFlags|=NODEFS.flagsForNodeMap[k];flags^=k}}if(flags){throw new FS.ErrnoError(28)}return newFlags},getattr(func,node){var stat=NODEFS.tryFSOperation(func);if(NODEFS.isWindows){if(!stat.blksize){stat.blksize=4096}if(!stat.blocks){stat.blocks=(stat.size+stat.blksize-1)/stat.blksize|0}stat.mode|=(stat.mode&292)>>2}return{dev:stat.dev,ino:node.id,mode:stat.mode,nlink:stat.nlink,uid:stat.uid,gid:stat.gid,rdev:stat.rdev,size:stat.size,atime:stat.atime,mtime:stat.mtime,ctime:stat.ctime,blksize:stat.blksize,blocks:stat.blocks}},setattr(arg,node,attr,chmod,utimes,truncate,stat){NODEFS.tryFSOperation(()=>{if(attr.mode!==undefined){var mode=attr.mode;if(NODEFS.isWindows){mode&=384}chmod(arg,mode);node.mode=attr.mode}if(typeof(attr.atime??attr.mtime)==="number"){var atime=new Date(attr.atime??stat(arg).atime);var mtime=new Date(attr.mtime??stat(arg).mtime);utimes(arg,atime,mtime)}if(attr.size!==undefined){truncate(arg,attr.size)}})},node_ops:{getattr(node){var path=NODEFS.realPath(node);return NODEFS.getattr(()=>fs.lstatSync(path),node)},setattr(node,attr){var path=NODEFS.realPath(node);if(attr.mode!=null&&attr.dontFollow){throw new FS.ErrnoError(52)}NODEFS.setattr(path,node,attr,fs.chmodSync,fs.utimesSync,fs.truncateSync,fs.lstatSync)},lookup(parent,name){var path=PATH.join2(NODEFS.realPath(parent),name);var mode=NODEFS.getMode(path);return NODEFS.createNode(parent,name,mode)},mknod(parent,name,mode,dev){var node=NODEFS.createNode(parent,name,mode,dev);var path=NODEFS.realPath(node);NODEFS.tryFSOperation(()=>{if(FS.isDir(node.mode)){fs.mkdirSync(path,node.mode)}else{fs.writeFileSync(path,"",{mode:node.mode})}});return node},rename(oldNode,newDir,newName){var oldPath=NODEFS.realPath(oldNode);var newPath=PATH.join2(NODEFS.realPath(newDir),newName);try{FS.unlink(newPath)}catch(e){}NODEFS.tryFSOperation(()=>fs.renameSync(oldPath,newPath));oldNode.name=newName},unlink(parent,name){var path=PATH.join2(NODEFS.realPath(parent),name);NODEFS.tryFSOperation(()=>fs.unlinkSync(path))},rmdir(parent,name){var path=PATH.join2(NODEFS.realPath(parent),name);NODEFS.tryFSOperation(()=>fs.rmdirSync(path))},readdir(node){var path=NODEFS.realPath(node);return NODEFS.tryFSOperation(()=>fs.readdirSync(path))},symlink(parent,newName,oldPath){var newPath=PATH.join2(NODEFS.realPath(parent),newName);NODEFS.tryFSOperation(()=>fs.symlinkSync(oldPath,newPath))},readlink(node){var path=NODEFS.realPath(node);return NODEFS.tryFSOperation(()=>fs.readlinkSync(path))},statfs(path){var stats=NODEFS.tryFSOperation(()=>fs.statfsSync(path));stats.frsize=stats.bsize;return stats}},stream_ops:{getattr(stream){return NODEFS.getattr(()=>fs.fstatSync(stream.nfd),stream.node)},setattr(stream,attr){NODEFS.setattr(stream.nfd,stream.node,attr,fs.fchmodSync,fs.futimesSync,fs.ftruncateSync,fs.fstatSync)},open(stream){var path=NODEFS.realPath(stream.node);NODEFS.tryFSOperation(()=>{stream.shared.refcount=1;stream.nfd=fs.openSync(path,NODEFS.flagsForNode(stream.flags))})},close(stream){NODEFS.tryFSOperation(()=>{if(stream.nfd&&--stream.shared.refcount===0){fs.closeSync(stream.nfd)}})},dup(stream){stream.shared.refcount++},read(stream,buffer,offset,length,position){return NODEFS.tryFSOperation(()=>fs.readSync(stream.nfd,buffer,offset,length,position))},write(stream,buffer,offset,length,position){return NODEFS.tryFSOperation(()=>fs.writeSync(stream.nfd,buffer,offset,length,position))},llseek(stream,offset,whence){var position=offset;if(whence===1){position+=stream.position}else if(whence===2){if(FS.isFile(stream.node.mode)){NODEFS.tryFSOperation(()=>{var stat=fs.fstatSync(stream.nfd);position+=stat.size})}}if(position<0){throw new FS.ErrnoError(28)}return position},mmap(stream,length,position,prot,flags){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}var ptr=mmapAlloc(length);NODEFS.stream_ops.read(stream,(growMemViews(),HEAP8),ptr,length,position);return{ptr,allocated:true}},msync(stream,buffer,offset,length,mmapFlags){NODEFS.stream_ops.write(stream,buffer,0,length,offset,false);return 0}}};var NODERAWFS_stream_funcs={close(stream){VFS.closeStream(stream.fd);if(--stream.shared.refcnt<=0&&stream.nfd>2){fs.closeSync(stream.nfd)}},llseek(stream,offset,whence){var position=offset;if(whence===1){position+=stream.position}else if(whence===2){position+=fs.fstatSync(stream.nfd).size}else if(whence!==0){throw new FS.ErrnoError(28)}if(position<0){throw new FS.ErrnoError(28)}stream.position=position;return position},read(stream,buffer,offset,length,position){var seeking=typeof position!="undefined";if(!seeking&&stream.seekable)position=stream.position;var bytesRead=fs.readSync(stream.nfd,buffer,offset,length,position);if(!seeking)stream.position+=bytesRead;return bytesRead},write(stream,buffer,offset,length,position){if(stream.flags&1024){FS.llseek(stream,0,2)}var seeking=typeof position!="undefined";if(!seeking&&stream.seekable)position=stream.position;var bytesWritten=fs.writeSync(stream.nfd,buffer,offset,length,position);if(!seeking)stream.position+=bytesWritten;return bytesWritten},mmap(stream,length,position,prot,flags){if(!length){throw new FS.ErrnoError(28)}var ptr=mmapAlloc(length);FS.read(stream,(growMemViews(),HEAP8),ptr,length,position);return{ptr,allocated:true}},msync(stream,buffer,offset,length,mmapFlags){FS.write(stream,buffer,0,length,offset);return 0},ioctl(stream,cmd,arg){throw new FS.ErrnoError(59)}};var NODERAWFS={lookup(parent,name){return FS.lookupPath(`${parent.path}/${name}`).node},lookupPath(path,opts={}){if(opts.parent){path=PATH.dirname(path)}var st=fs.lstatSync(path);var mode=NODEFS.getMode(path);return{path,node:{id:st.ino,mode,node_ops:NODERAWFS,path}}},createStandardStreams(){FS.createStream({nfd:0,position:0,path:"/dev/stdin",flags:0,seekable:false},0);var paths=[,"/dev/stdout","/dev/stderr"];for(var i=1;i<3;i++){FS.createStream({nfd:i,position:0,path:paths[i],flags:577,seekable:false},i)}},cwd(){return process.cwd()},chdir(...args){process.chdir(...args)},mknod(path,mode){if(FS.isDir(path)){fs.mkdirSync(path,mode)}else{fs.writeFileSync(path,"",{mode})}},mkdir(...args){fs.mkdirSync(...args)},symlink(...args){fs.symlinkSync(...args)},rename(...args){fs.renameSync(...args)},rmdir(...args){fs.rmdirSync(...args)},readdir(...args){return[".",".."].concat(fs.readdirSync(...args))},unlink(...args){fs.unlinkSync(...args)},readlink(...args){return fs.readlinkSync(...args)},stat(path,dontFollow){var stat=dontFollow?fs.lstatSync(path):fs.statSync(path);if(NODEFS.isWindows){stat.mode|=(stat.mode&292)>>2}return stat},fstat(fd){var stream=FS.getStreamChecked(fd);return fs.fstatSync(stream.nfd)},statfs(path){var defaults={fsid:42,flags:2,namelen:255};return Object.assign(defaults,fs.statfsSync(path))},statfsStream(stream){return FS.statfs(stream.path)},chmod(path,mode,dontFollow){mode&=4095;if(NODEFS.isWindows){mode&=384}if(dontFollow&&fs.lstatSync(path).isSymbolicLink()){throw new FS.ErrnoError(138)}fs.chmodSync(path,mode)},fchmod(fd,mode){var stream=FS.getStreamChecked(fd);fs.fchmodSync(stream.nfd,mode)},chown(...args){fs.chownSync(...args)},fchown(fd,owner,group){var stream=FS.getStreamChecked(fd);fs.fchownSync(stream.nfd,owner,group)},truncate(path,len){if(len<0){throw new FS.ErrnoError(28)}return fs.truncateSync(path,len)},ftruncate(fd,len){if(len<0){throw new FS.ErrnoError(28)}var stream=FS.getStreamChecked(fd);fs.ftruncateSync(stream.nfd,len)},utime(path,atime,mtime){if(atime===null||mtime===null){var st=fs.statSync(path);atime||=st.atimeMs;mtime||=st.mtimeMs}fs.utimesSync(path,atime/1e3,mtime/1e3)},open(path,flags,mode){flags=FS_modeStringToFlags(flags);var pathTruncated=path.split("/").map(s=>s.slice(0,255)).join("/");var nfd=fs.openSync(pathTruncated,NODEFS.flagsForNode(flags),mode);var st=fs.fstatSync(nfd);if(flags&65536&&!st.isDirectory()){fs.closeSync(nfd);throw new FS.ErrnoError(ERRNO_CODES.ENOTDIR)}var newMode=NODEFS.getMode(pathTruncated);var node={id:st.ino,mode:newMode,node_ops:NODERAWFS,path};return FS.createStream({nfd,position:0,path,flags,node,seekable:true})},createStream(stream,fd){var rtn=VFS.createStream(stream,fd);if(!stream.stream_ops){rtn.shared.refcnt??=0;rtn.shared.refcnt++;rtn.tty=nodeTTY.isatty(rtn.nfd)}return rtn}};var asyncLoad=async url=>{var arrayBuffer=await readAsync(url);return new Uint8Array(arrayBuffer)};var FS_createDataFile=(...args)=>FS.createDataFile(...args);var getUniqueRunDependency=id=>id;var runDependencies=0;var dependenciesFulfilled=null;var removeRunDependency=id=>{runDependencies--;Module["monitorRunDependencies"]?.(runDependencies);if(runDependencies==0){if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}};var addRunDependency=id=>{runDependencies++;Module["monitorRunDependencies"]?.(runDependencies)};var preloadPlugins=[];var FS_handledByPreloadPlugin=async(byteArray,fullname)=>{if(typeof Browser!="undefined")Browser.init();for(var plugin of preloadPlugins){if(plugin["canHandle"](fullname)){return plugin["handle"](byteArray,fullname)}}return byteArray};var FS_preloadFile=async(parent,name,url,canRead,canWrite,dontCreateFile,canOwn,preFinish)=>{var fullname=name?PATH_FS.resolve(PATH.join2(parent,name)):parent;var dep=getUniqueRunDependency(`cp ${fullname}`);addRunDependency(dep);try{var byteArray=url;if(typeof url=="string"){byteArray=await asyncLoad(url)}byteArray=await FS_handledByPreloadPlugin(byteArray,fullname);preFinish?.();if(!dontCreateFile){FS_createDataFile(parent,name,byteArray,canRead,canWrite,canOwn)}}finally{removeRunDependency(dep)}};var FS_createPreloadedFile=(parent,name,url,canRead,canWrite,onload,onerror,dontCreateFile,canOwn,preFinish)=>{FS_preloadFile(parent,name,url,canRead,canWrite,dontCreateFile,canOwn,preFinish).then(onload).catch(onerror)};var FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:false,ignorePermissions:true,filesystems:null,syncFSRequests:0,ErrnoError:class{name="ErrnoError";constructor(errno){this.errno=errno}},FSStream:class{shared={};get object(){return this.node}set object(val){this.node=val}get isRead(){return(this.flags&2097155)!==1}get isWrite(){return(this.flags&2097155)!==0}get isAppend(){return this.flags&1024}get flags(){return this.shared.flags}set flags(val){this.shared.flags=val}get position(){return this.shared.position}set position(val){this.shared.position=val}},FSNode:class{node_ops={};stream_ops={};readMode=292|73;writeMode=146;mounted=null;constructor(parent,name,mode,rdev){if(!parent){parent=this}this.parent=parent;this.mount=parent.mount;this.id=FS.nextInode++;this.name=name;this.mode=mode;this.rdev=rdev;this.atime=this.mtime=this.ctime=Date.now()}get read(){return(this.mode&this.readMode)===this.readMode}set read(val){val?this.mode|=this.readMode:this.mode&=~this.readMode}get write(){return(this.mode&this.writeMode)===this.writeMode}set write(val){val?this.mode|=this.writeMode:this.mode&=~this.writeMode}get isFolder(){return FS.isDir(this.mode)}get isDevice(){return FS.isChrdev(this.mode)}},lookupPath(path,opts={}){if(!path){throw new FS.ErrnoError(44)}opts.follow_mount??=true;if(!PATH.isAbs(path)){path=FS.cwd()+"/"+path}linkloop:for(var nlinks=0;nlinks<40;nlinks++){var parts=path.split("/").filter(p=>!!p);var current=FS.root;var current_path="/";for(var i=0;i>>0)%FS.nameTable.length},hashAddNode(node){var hash=FS.hashName(node.parent.id,node.name);node.name_next=FS.nameTable[hash];FS.nameTable[hash]=node},hashRemoveNode(node){var hash=FS.hashName(node.parent.id,node.name);if(FS.nameTable[hash]===node){FS.nameTable[hash]=node.name_next}else{var current=FS.nameTable[hash];while(current){if(current.name_next===node){current.name_next=node.name_next;break}current=current.name_next}}},lookupNode(parent,name){var errCode=FS.mayLookup(parent);if(errCode){throw new FS.ErrnoError(errCode)}var hash=FS.hashName(parent.id,name);for(var node=FS.nameTable[hash];node;node=node.name_next){var nodeName=node.name;if(node.parent.id===parent.id&&nodeName===name){return node}}return FS.lookup(parent,name)},createNode(parent,name,mode,rdev){var node=new FS.FSNode(parent,name,mode,rdev);FS.hashAddNode(node);return node},destroyNode(node){FS.hashRemoveNode(node)},isRoot(node){return node===node.parent},isMountpoint(node){return!!node.mounted},isFile(mode){return(mode&61440)===32768},isDir(mode){return(mode&61440)===16384},isLink(mode){return(mode&61440)===40960},isChrdev(mode){return(mode&61440)===8192},isBlkdev(mode){return(mode&61440)===24576},isFIFO(mode){return(mode&61440)===4096},isSocket(mode){return(mode&49152)===49152},flagsToPermissionString(flag){var perms=["r","w","rw"][flag&3];if(flag&512){perms+="w"}return perms},nodePermissions(node,perms){if(FS.ignorePermissions){return 0}if(perms.includes("r")&&!(node.mode&292)){return 2}if(perms.includes("w")&&!(node.mode&146)){return 2}if(perms.includes("x")&&!(node.mode&73)){return 2}return 0},mayLookup(dir){if(!FS.isDir(dir.mode))return 54;var errCode=FS.nodePermissions(dir,"x");if(errCode)return errCode;if(!dir.node_ops.lookup)return 2;return 0},mayCreate(dir,name){if(!FS.isDir(dir.mode)){return 54}try{var node=FS.lookupNode(dir,name);return 20}catch(e){}return FS.nodePermissions(dir,"wx")},mayDelete(dir,name,isdir){var node;try{node=FS.lookupNode(dir,name)}catch(e){return e.errno}var errCode=FS.nodePermissions(dir,"wx");if(errCode){return errCode}if(isdir){if(!FS.isDir(node.mode)){return 54}if(FS.isRoot(node)||FS.getPath(node)===FS.cwd()){return 10}}else if(FS.isDir(node.mode)){return 31}return 0},mayOpen(node,flags){if(!node){return 44}if(FS.isLink(node.mode)){return 32}var mode=FS.flagsToPermissionString(flags);if(FS.isDir(node.mode)){if(mode!=="r"||flags&(512|64)){return 31}}return FS.nodePermissions(node,mode)},checkOpExists(op,err){if(!op){throw new FS.ErrnoError(err)}return op},MAX_OPEN_FDS:4096,nextfd(){for(var fd=0;fd<=FS.MAX_OPEN_FDS;fd++){if(!FS.streams[fd]){return fd}}throw new FS.ErrnoError(33)},getStreamChecked(fd){var stream=FS.getStream(fd);if(!stream){throw new FS.ErrnoError(8)}return stream},getStream:fd=>FS.streams[fd],createStream(stream,fd=-1){stream=Object.assign(new FS.FSStream,stream);if(fd==-1){fd=FS.nextfd()}stream.fd=fd;FS.streams[fd]=stream;return stream},closeStream(fd){FS.streams[fd]=null},dupStream(origStream,fd=-1){var stream=FS.createStream(origStream,fd);stream.stream_ops?.dup?.(stream);return stream},doSetAttr(stream,node,attr){var setattr=stream?.stream_ops.setattr;var arg=setattr?stream:node;setattr??=node.node_ops.setattr;FS.checkOpExists(setattr,63);try{setattr(arg,attr)}catch(e){if(e instanceof RangeError){throw new FS.ErrnoError(22)}throw e}},chrdev_stream_ops:{open(stream){var device=FS.getDevice(stream.node.rdev);stream.stream_ops=device.stream_ops;stream.stream_ops.open?.(stream)},llseek(){throw new FS.ErrnoError(70)}},major:dev=>dev>>8,minor:dev=>dev&255,makedev:(ma,mi)=>ma<<8|mi,registerDevice(dev,ops){FS.devices[dev]={stream_ops:ops}},getDevice:dev=>FS.devices[dev],getMounts(mount){var mounts=[];var check=[mount];while(check.length){var m=check.pop();mounts.push(m);check.push(...m.mounts)}return mounts},syncfs(populate,callback){if(typeof populate=="function"){callback=populate;populate=false}FS.syncFSRequests++;if(FS.syncFSRequests>1){err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`)}var mounts=FS.getMounts(FS.root.mount);var completed=0;function doCallback(errCode){FS.syncFSRequests--;return callback(errCode)}function done(errCode){if(errCode){if(!done.errored){done.errored=true;return doCallback(errCode)}return}if(++completed>=mounts.length){doCallback(null)}}for(var mount of mounts){if(mount.type.syncfs){mount.type.syncfs(mount,populate,done)}else{done(null)}}},mount(type,opts,mountpoint){var root=mountpoint==="/";var pseudo=!mountpoint;var node;if(root&&FS.root){throw new FS.ErrnoError(10)}else if(!root&&!pseudo){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});mountpoint=lookup.path;node=lookup.node;if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}if(!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}}var mount={type,opts,mountpoint,mounts:[]};var mountRoot=type.mount(mount);mountRoot.mount=mount;mount.root=mountRoot;if(root){FS.root=mountRoot}else if(node){node.mounted=mount;if(node.mount){node.mount.mounts.push(mount)}}return mountRoot},unmount(mountpoint){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});if(!FS.isMountpoint(lookup.node)){throw new FS.ErrnoError(28)}var node=lookup.node;var mount=node.mounted;var mounts=FS.getMounts(mount);for(var[hash,current]of Object.entries(FS.nameTable)){while(current){var next=current.name_next;if(mounts.includes(current.mount)){FS.destroyNode(current)}current=next}}node.mounted=null;var idx=node.mount.mounts.indexOf(mount);node.mount.mounts.splice(idx,1)},lookup(parent,name){return parent.node_ops.lookup(parent,name)},mknod(path,mode,dev){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);if(!name){throw new FS.ErrnoError(28)}if(name==="."||name===".."){throw new FS.ErrnoError(20)}var errCode=FS.mayCreate(parent,name);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.mknod){throw new FS.ErrnoError(63)}return parent.node_ops.mknod(parent,name,mode,dev)},statfs(path){return FS.statfsNode(FS.lookupPath(path,{follow:true}).node)},statfsStream(stream){return FS.statfsNode(stream.node)},statfsNode(node){var rtn={bsize:4096,frsize:4096,blocks:1e6,bfree:5e5,bavail:5e5,files:FS.nextInode,ffree:FS.nextInode-1,fsid:42,flags:2,namelen:255};if(node.node_ops.statfs){Object.assign(rtn,node.node_ops.statfs(node.mount.opts.root))}return rtn},create(path,mode=438){mode&=4095;mode|=32768;return FS.mknod(path,mode,0)},mkdir(path,mode=511){mode&=511|512;mode|=16384;return FS.mknod(path,mode,0)},mkdirTree(path,mode){var dirs=path.split("/");var d="";for(var dir of dirs){if(!dir)continue;if(d||PATH.isAbs(path))d+="/";d+=dir;try{FS.mkdir(d,mode)}catch(e){if(e.errno!=20)throw e}}},mkdev(path,mode,dev){if(typeof dev=="undefined"){dev=mode;mode=438}mode|=8192;return FS.mknod(path,mode,dev)},symlink(oldpath,newpath){if(!PATH_FS.resolve(oldpath)){throw new FS.ErrnoError(44)}var lookup=FS.lookupPath(newpath,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var newname=PATH.basename(newpath);var errCode=FS.mayCreate(parent,newname);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.symlink){throw new FS.ErrnoError(63)}return parent.node_ops.symlink(parent,newname,oldpath)},rename(old_path,new_path){var old_dirname=PATH.dirname(old_path);var new_dirname=PATH.dirname(new_path);var old_name=PATH.basename(old_path);var new_name=PATH.basename(new_path);var lookup,old_dir,new_dir;lookup=FS.lookupPath(old_path,{parent:true});old_dir=lookup.node;lookup=FS.lookupPath(new_path,{parent:true});new_dir=lookup.node;if(!old_dir||!new_dir)throw new FS.ErrnoError(44);if(old_dir.mount!==new_dir.mount){throw new FS.ErrnoError(75)}var old_node=FS.lookupNode(old_dir,old_name);var relative=PATH_FS.relative(old_path,new_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(28)}relative=PATH_FS.relative(new_path,old_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(55)}var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(old_node===new_node){return}var isdir=FS.isDir(old_node.mode);var errCode=FS.mayDelete(old_dir,old_name,isdir);if(errCode){throw new FS.ErrnoError(errCode)}errCode=new_node?FS.mayDelete(new_dir,new_name,isdir):FS.mayCreate(new_dir,new_name);if(errCode){throw new FS.ErrnoError(errCode)}if(!old_dir.node_ops.rename){throw new FS.ErrnoError(63)}if(FS.isMountpoint(old_node)||new_node&&FS.isMountpoint(new_node)){throw new FS.ErrnoError(10)}if(new_dir!==old_dir){errCode=FS.nodePermissions(old_dir,"w");if(errCode){throw new FS.ErrnoError(errCode)}}FS.hashRemoveNode(old_node);try{old_dir.node_ops.rename(old_node,new_dir,new_name);old_node.parent=new_dir}catch(e){throw e}finally{FS.hashAddNode(old_node)}},rmdir(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,true);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.rmdir){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.rmdir(parent,name);FS.destroyNode(node)},readdir(path){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;var readdir=FS.checkOpExists(node.node_ops.readdir,54);return readdir(node)},unlink(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,false);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.unlink){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.unlink(parent,name);FS.destroyNode(node)},readlink(path){var lookup=FS.lookupPath(path);var link=lookup.node;if(!link){throw new FS.ErrnoError(44)}if(!link.node_ops.readlink){throw new FS.ErrnoError(28)}return link.node_ops.readlink(link)},stat(path,dontFollow){var lookup=FS.lookupPath(path,{follow:!dontFollow});var node=lookup.node;var getattr=FS.checkOpExists(node.node_ops.getattr,63);return getattr(node)},fstat(fd){var stream=FS.getStreamChecked(fd);var node=stream.node;var getattr=stream.stream_ops.getattr;var arg=getattr?stream:node;getattr??=node.node_ops.getattr;FS.checkOpExists(getattr,63);return getattr(arg)},lstat(path){return FS.stat(path,true)},doChmod(stream,node,mode,dontFollow){FS.doSetAttr(stream,node,{mode:mode&4095|node.mode&~4095,ctime:Date.now(),dontFollow})},chmod(path,mode,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChmod(null,node,mode,dontFollow)},lchmod(path,mode){FS.chmod(path,mode,true)},fchmod(fd,mode){var stream=FS.getStreamChecked(fd);FS.doChmod(stream,stream.node,mode,false)},doChown(stream,node,dontFollow){FS.doSetAttr(stream,node,{timestamp:Date.now(),dontFollow})},chown(path,uid,gid,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChown(null,node,dontFollow)},lchown(path,uid,gid){FS.chown(path,uid,gid,true)},fchown(fd,uid,gid){var stream=FS.getStreamChecked(fd);FS.doChown(stream,stream.node,false)},doTruncate(stream,node,len){if(FS.isDir(node.mode)){throw new FS.ErrnoError(31)}if(!FS.isFile(node.mode)){throw new FS.ErrnoError(28)}var errCode=FS.nodePermissions(node,"w");if(errCode){throw new FS.ErrnoError(errCode)}FS.doSetAttr(stream,node,{size:len,timestamp:Date.now()})},truncate(path,len){if(len<0){throw new FS.ErrnoError(28)}var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:true});node=lookup.node}else{node=path}FS.doTruncate(null,node,len)},ftruncate(fd,len){var stream=FS.getStreamChecked(fd);if(len<0||(stream.flags&2097155)===0){throw new FS.ErrnoError(28)}FS.doTruncate(stream,stream.node,len)},utime(path,atime,mtime){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;var setattr=FS.checkOpExists(node.node_ops.setattr,63);setattr(node,{atime,mtime})},open(path,flags,mode=438){if(path===""){throw new FS.ErrnoError(44)}flags=FS_modeStringToFlags(flags);if(flags&64){mode=mode&4095|32768}else{mode=0}var node;var isDirPath;if(typeof path=="object"){node=path}else{isDirPath=path.endsWith("/");var lookup=FS.lookupPath(path,{follow:!(flags&131072),noent_okay:true});node=lookup.node;path=lookup.path}var created=false;if(flags&64){if(node){if(flags&128){throw new FS.ErrnoError(20)}}else if(isDirPath){throw new FS.ErrnoError(31)}else{node=FS.mknod(path,mode|511,0);created=true}}if(!node){throw new FS.ErrnoError(44)}if(FS.isChrdev(node.mode)){flags&=~512}if(flags&65536&&!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}if(!created){var errCode=FS.mayOpen(node,flags);if(errCode){throw new FS.ErrnoError(errCode)}}if(flags&512&&!created){FS.truncate(node,0)}flags&=~(128|512|131072);var stream=FS.createStream({node,path:FS.getPath(node),flags,seekable:true,position:0,stream_ops:node.stream_ops,ungotten:[],error:false});if(stream.stream_ops.open){stream.stream_ops.open(stream)}if(created){FS.chmod(node,mode&511)}return stream},close(stream){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(stream.getdents)stream.getdents=null;try{if(stream.stream_ops.close){stream.stream_ops.close(stream)}}catch(e){throw e}finally{FS.closeStream(stream.fd)}stream.fd=null},isClosed(stream){return stream.fd===null},llseek(stream,offset,whence){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(!stream.seekable||!stream.stream_ops.llseek){throw new FS.ErrnoError(70)}if(whence!=0&&whence!=1&&whence!=2){throw new FS.ErrnoError(28)}stream.position=stream.stream_ops.llseek(stream,offset,whence);stream.ungotten=[];return stream.position},read(stream,buffer,offset,length,position){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.read){throw new FS.ErrnoError(28)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesRead=stream.stream_ops.read(stream,buffer,offset,length,position);if(!seeking)stream.position+=bytesRead;return bytesRead},write(stream,buffer,offset,length,position,canOwn){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===0){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.write){throw new FS.ErrnoError(28)}if(stream.seekable&&stream.flags&1024){FS.llseek(stream,0,2)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesWritten=stream.stream_ops.write(stream,buffer,offset,length,position,canOwn);if(!seeking)stream.position+=bytesWritten;return bytesWritten},mmap(stream,length,position,prot,flags){if((prot&2)!==0&&(flags&2)===0&&(stream.flags&2097155)!==2){throw new FS.ErrnoError(2)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(2)}if(!stream.stream_ops.mmap){throw new FS.ErrnoError(43)}if(!length){throw new FS.ErrnoError(28)}return stream.stream_ops.mmap(stream,length,position,prot,flags)},msync(stream,buffer,offset,length,mmapFlags){if(!stream.stream_ops.msync){return 0}return stream.stream_ops.msync(stream,buffer,offset,length,mmapFlags)},ioctl(stream,cmd,arg){if(!stream.stream_ops.ioctl){throw new FS.ErrnoError(59)}return stream.stream_ops.ioctl(stream,cmd,arg)},readFile(path,opts={}){opts.flags=opts.flags??0;opts.encoding=opts.encoding??"binary";if(opts.encoding!=="utf8"&&opts.encoding!=="binary"){abort(`Invalid encoding type "${opts.encoding}"`)}var stream=FS.open(path,opts.flags);var stat=FS.stat(path);var length=stat.size;var buf=new Uint8Array(length);FS.read(stream,buf,0,length,0);if(opts.encoding==="utf8"){buf=UTF8ArrayToString(buf)}FS.close(stream);return buf},writeFile(path,data,opts={}){opts.flags=opts.flags??577;var stream=FS.open(path,opts.flags,opts.mode);data=FS_fileDataToTypedArray(data);FS.write(stream,data,0,data.byteLength,undefined,opts.canOwn);FS.close(stream)},cwd:()=>FS.currentPath,chdir(path){var lookup=FS.lookupPath(path,{follow:true});if(lookup.node===null){throw new FS.ErrnoError(44)}if(!FS.isDir(lookup.node.mode)){throw new FS.ErrnoError(54)}var errCode=FS.nodePermissions(lookup.node,"x");if(errCode){throw new FS.ErrnoError(errCode)}FS.currentPath=lookup.path},createDefaultDirectories(){FS.mkdir("/tmp");FS.mkdir("/home");FS.mkdir("/home/web_user")},createDefaultDevices(){FS.mkdir("/dev");FS.registerDevice(FS.makedev(1,3),{read:()=>0,write:(stream,buffer,offset,length,pos)=>length,llseek:()=>0});FS.mkdev("/dev/null",FS.makedev(1,3));TTY.register(FS.makedev(5,0),TTY.default_tty_ops);TTY.register(FS.makedev(6,0),TTY.default_tty1_ops);FS.mkdev("/dev/tty",FS.makedev(5,0));FS.mkdev("/dev/tty1",FS.makedev(6,0));var randomBuffer=new Uint8Array(1024),randomLeft=0;var randomByte=()=>{if(randomLeft===0){randomFill(randomBuffer);randomLeft=randomBuffer.byteLength}return randomBuffer[--randomLeft]};FS.createDevice("/dev","random",randomByte);FS.createDevice("/dev","urandom",randomByte);FS.mkdir("/dev/shm");FS.mkdir("/dev/shm/tmp")},createSpecialDirectories(){FS.mkdir("/proc");var proc_self=FS.mkdir("/proc/self");FS.mkdir("/proc/self/fd");FS.mount({mount(){var node=FS.createNode(proc_self,"fd",16895,73);node.stream_ops={llseek:MEMFS.stream_ops.llseek};node.node_ops={lookup(parent,name){var fd=+name;var stream=FS.getStreamChecked(fd);var ret={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>stream.path},id:fd+1};ret.parent=ret;return ret},readdir(){return Array.from(FS.streams.entries()).filter(([k,v])=>v).map(([k,v])=>k.toString())}};return node}},{},"/proc/self/fd")},createStandardStreams(input,output,error){if(input){FS.createDevice("/dev","stdin",input)}else{FS.symlink("/dev/tty","/dev/stdin")}if(output){FS.createDevice("/dev","stdout",null,output)}else{FS.symlink("/dev/tty","/dev/stdout")}if(error){FS.createDevice("/dev","stderr",null,error)}else{FS.symlink("/dev/tty1","/dev/stderr")}var stdin=FS.open("/dev/stdin",0);var stdout=FS.open("/dev/stdout",1);var stderr=FS.open("/dev/stderr",1)},staticInit(){FS.nameTable=new Array(4096);FS.mount(MEMFS,{},"/");FS.createDefaultDirectories();FS.createDefaultDevices();FS.createSpecialDirectories();FS.filesystems={MEMFS,NODEFS}},init(input,output,error){FS.initialized=true;input??=Module["stdin"];output??=Module["stdout"];error??=Module["stderr"];FS.createStandardStreams(input,output,error)},quit(){FS.initialized=false;for(var stream of FS.streams){if(stream){FS.close(stream)}}},findObject(path,dontResolveLastLink){var ret=FS.analyzePath(path,dontResolveLastLink);if(!ret.exists){return null}return ret.object},analyzePath(path,dontResolveLastLink){try{var lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});path=lookup.path}catch(e){}var ret={isRoot:false,exists:false,error:0,name:null,path:null,object:null,parentExists:false,parentPath:null,parentObject:null};try{var lookup=FS.lookupPath(path,{parent:true});ret.parentExists=true;ret.parentPath=lookup.path;ret.parentObject=lookup.node;ret.name=PATH.basename(path);lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});ret.exists=true;ret.path=lookup.path;ret.object=lookup.node;ret.name=lookup.node.name;ret.isRoot=lookup.path==="/"}catch(e){ret.error=e.errno}return ret},createPath(parent,path,canRead,canWrite){parent=typeof parent=="string"?parent:FS.getPath(parent);var parts=path.split("/").reverse();while(parts.length){var part=parts.pop();if(!part)continue;var current=PATH.join2(parent,part);try{FS.mkdir(current)}catch(e){if(e.errno!=20)throw e}parent=current}return current},createFile(parent,name,properties,canRead,canWrite){var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(canRead,canWrite);return FS.create(path,mode)},createDataFile(parent,name,data,canRead,canWrite,canOwn){var path=name;if(parent){parent=typeof parent=="string"?parent:FS.getPath(parent);path=name?PATH.join2(parent,name):parent}var mode=FS_getMode(canRead,canWrite);var node=FS.create(path,mode);if(data){data=FS_fileDataToTypedArray(data);FS.chmod(node,mode|146);var stream=FS.open(node,577);FS.write(stream,data,0,data.length,0,canOwn);FS.close(stream);FS.chmod(node,mode)}},createDevice(parent,name,input,output){var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(!!input,!!output);FS.createDevice.major??=64;var dev=FS.makedev(FS.createDevice.major++,0);FS.registerDevice(dev,{open(stream){stream.seekable=false},close(stream){if(output?.buffer?.length){output(10)}},read(stream,buffer,offset,length,pos){var bytesRead=0;for(var i=0;ithis.length-1||idx<0){return undefined}var chunkOffset=idx%this.chunkSize;var chunkNum=idx/this.chunkSize|0;return this.getter(chunkNum)[chunkOffset]}setDataGetter(getter){this.getter=getter}cacheLength(){var xhr=new XMLHttpRequest;xhr.open("HEAD",url,false);xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))abort("Couldn't load "+url+". Status: "+xhr.status);var datalength=Number(xhr.getResponseHeader("Content-length"));var header;var hasByteServing=(header=xhr.getResponseHeader("Accept-Ranges"))&&header==="bytes";var usesGzip=(header=xhr.getResponseHeader("Content-Encoding"))&&header==="gzip";var chunkSize=1024*1024;if(!hasByteServing)chunkSize=datalength;var doXHR=(from,to)=>{if(from>to)abort(`invalid range (${from}, ${to}) or no bytes requested!`);if(to>datalength-1)abort(`only ${datalength} bytes available! programmer error!`);var xhr=new XMLHttpRequest;xhr.open("GET",url,false);if(datalength!==chunkSize)xhr.setRequestHeader("Range","bytes="+from+"-"+to);xhr.responseType="arraybuffer";if(xhr.overrideMimeType){xhr.overrideMimeType("text/plain; charset=x-user-defined")}xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))abort("Couldn't load "+url+". Status: "+xhr.status);if(xhr.response!==undefined){return new Uint8Array(xhr.response||[])}return intArrayFromString(xhr.responseText??"",true)};var lazyArray=this;lazyArray.setDataGetter(chunkNum=>{var start=chunkNum*chunkSize;var end=(chunkNum+1)*chunkSize-1;end=Math.min(end,datalength-1);if(typeof lazyArray.chunks[chunkNum]=="undefined"){lazyArray.chunks[chunkNum]=doXHR(start,end)}if(typeof lazyArray.chunks[chunkNum]=="undefined")abort("doXHR failed!");return lazyArray.chunks[chunkNum]});if(usesGzip||!datalength){chunkSize=datalength=1;datalength=this.getter(0).length;chunkSize=datalength;out("LazyFiles on gzip forces download of the whole file when length is accessed")}this._length=datalength;this._chunkSize=chunkSize;this.lengthKnown=true}get length(){if(!this.lengthKnown){this.cacheLength()}return this._length}get chunkSize(){if(!this.lengthKnown){this.cacheLength()}return this._chunkSize}}if(globalThis.XMLHttpRequest){if(!ENVIRONMENT_IS_WORKER)abort("Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc");var lazyArray=new LazyUint8Array;var properties={isDevice:false,contents:lazyArray}}else{var properties={isDevice:false,url}}var node=FS.createFile(parent,name,properties,canRead,canWrite);if(properties.contents){node.contents=properties.contents}else if(properties.url){node.contents=null;node.url=properties.url}Object.defineProperties(node,{usedBytes:{get:function(){return this.contents.length}}});var stream_ops={};for(const[key,fn]of Object.entries(node.stream_ops)){stream_ops[key]=(...args)=>{FS.forceLoadFile(node);return fn(...args)}}function writeChunks(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=contents.length)return 0;var size=Math.min(contents.length-position,length);if(contents.slice){for(var i=0;i{FS.forceLoadFile(node);return writeChunks(stream,buffer,offset,length,position)};stream_ops.mmap=(stream,length,position,prot,flags)=>{FS.forceLoadFile(node);var ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}writeChunks(stream,(growMemViews(),HEAP8),ptr,length,position);return{ptr,allocated:true}};node.stream_ops=stream_ops;return node}};var SYSCALLS={currentUmask:18,calculateAt(dirfd,path,allowEmpty){if(PATH.isAbs(path)){return path}var dir;if(dirfd===-100){dir=FS.cwd()}else{var dirstream=SYSCALLS.getStreamFromFD(dirfd);dir=dirstream.path}if(path.length==0){if(!allowEmpty){throw new FS.ErrnoError(44)}return dir}return dir+"/"+path},writeStat(buf,stat){(growMemViews(),HEAPU32)[buf>>2]=stat.dev;(growMemViews(),HEAPU32)[buf+4>>2]=stat.mode;(growMemViews(),HEAPU32)[buf+8>>2]=stat.nlink;(growMemViews(),HEAPU32)[buf+12>>2]=stat.uid;(growMemViews(),HEAPU32)[buf+16>>2]=stat.gid;(growMemViews(),HEAPU32)[buf+20>>2]=stat.rdev;(growMemViews(),HEAP64)[buf+24>>3]=BigInt(stat.size);(growMemViews(),HEAP32)[buf+32>>2]=4096;(growMemViews(),HEAP32)[buf+36>>2]=stat.blocks;var atime=stat.atime.getTime();var mtime=stat.mtime.getTime();var ctime=stat.ctime.getTime();(growMemViews(),HEAP64)[buf+40>>3]=BigInt(Math.floor(atime/1e3));(growMemViews(),HEAPU32)[buf+48>>2]=atime%1e3*1e3*1e3;(growMemViews(),HEAP64)[buf+56>>3]=BigInt(Math.floor(mtime/1e3));(growMemViews(),HEAPU32)[buf+64>>2]=mtime%1e3*1e3*1e3;(growMemViews(),HEAP64)[buf+72>>3]=BigInt(Math.floor(ctime/1e3));(growMemViews(),HEAPU32)[buf+80>>2]=ctime%1e3*1e3*1e3;(growMemViews(),HEAP64)[buf+88>>3]=BigInt(stat.ino);return 0},writeStatFs(buf,stats){(growMemViews(),HEAPU32)[buf+4>>2]=stats.bsize;(growMemViews(),HEAPU32)[buf+60>>2]=stats.bsize;(growMemViews(),HEAP64)[buf+8>>3]=BigInt(stats.blocks);(growMemViews(),HEAP64)[buf+16>>3]=BigInt(stats.bfree);(growMemViews(),HEAP64)[buf+24>>3]=BigInt(stats.bavail);(growMemViews(),HEAP64)[buf+32>>3]=BigInt(stats.files);(growMemViews(),HEAP64)[buf+40>>3]=BigInt(stats.ffree);(growMemViews(),HEAPU32)[buf+48>>2]=stats.fsid;(growMemViews(),HEAPU32)[buf+64>>2]=stats.flags;(growMemViews(),HEAPU32)[buf+56>>2]=stats.namelen},doMsync(addr,stream,len,flags,offset){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}if(flags&2){return 0}var buffer=(growMemViews(),HEAPU8).subarray(addr,addr+len);FS.msync(stream,buffer,offset,len,flags)},getStreamFromFD(fd){var stream=FS.getStreamChecked(fd);return stream},varargs:undefined,getStr(ptr){var ret=UTF8ToString(ptr);return ret}};function ___syscall_dup(fd){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(3,0,1,fd);try{var old=SYSCALLS.getStreamFromFD(fd);return FS.dupStream(old).fd}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_faccessat(dirfd,path,amode,flags){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(4,0,1,dirfd,path,amode,flags);try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);if(amode&~7){return-28}var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;if(!node){return-44}var perms="";if(amode&4)perms+="r";if(amode&2)perms+="w";if(amode&1)perms+="x";if(perms&&FS.nodePermissions(node,perms)){return-2}return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var syscallGetVarargI=()=>{var ret=(growMemViews(),HEAP32)[+SYSCALLS.varargs>>2];SYSCALLS.varargs+=4;return ret};var syscallGetVarargP=syscallGetVarargI;function ___syscall_fcntl64(fd,cmd,varargs){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(5,0,1,fd,cmd,varargs);SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(cmd){case 0:{var arg=syscallGetVarargI();if(arg<0){return-28}while(FS.streams[arg]){arg++}var newStream;newStream=FS.dupStream(stream,arg);return newStream.fd}case 1:case 2:return 0;case 3:return stream.flags;case 4:{var arg=syscallGetVarargI();var mask=289792;stream.flags=stream.flags&~mask|arg&mask;return 0}case 12:{var arg=syscallGetVarargP();var offset=0;(growMemViews(),HEAP16)[arg+offset>>1]=2;return 0}case 13:case 14:return 0}return-28}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_fstat64(fd,buf){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(6,0,1,fd,buf);try{return SYSCALLS.writeStat(buf,FS.fstat(fd))}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var INT53_MAX=9007199254740992;var INT53_MIN=-9007199254740992;var bigintToI53Checked=num=>numINT53_MAX?NaN:Number(num);function ___syscall_ftruncate64(fd,length){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(7,0,1,fd,length);length=bigintToI53Checked(length);try{if(isNaN(length))return-22;FS.ftruncate(fd,length);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,(growMemViews(),HEAPU8),outPtr,maxBytesToWrite);function ___syscall_getcwd(buf,size){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(8,0,1,buf,size);try{if(size===0)return-28;var cwd=FS.cwd();var cwdLengthInBytes=lengthBytesUTF8(cwd)+1;if(size>2]=termios.c_iflag||0;(growMemViews(),HEAP32)[argp+4>>2]=termios.c_oflag||0;(growMemViews(),HEAP32)[argp+8>>2]=termios.c_cflag||0;(growMemViews(),HEAP32)[argp+12>>2]=termios.c_lflag||0;for(var i=0;i<32;i++){(growMemViews(),HEAP8)[argp+i+17]=termios.c_cc[i]||0}return 0}return 0}case 21510:case 21511:case 21512:{if(!stream.tty)return-59;return 0}case 21506:case 21507:case 21508:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcsets){var argp=syscallGetVarargP();var c_iflag=(growMemViews(),HEAP32)[argp>>2];var c_oflag=(growMemViews(),HEAP32)[argp+4>>2];var c_cflag=(growMemViews(),HEAP32)[argp+8>>2];var c_lflag=(growMemViews(),HEAP32)[argp+12>>2];var c_cc=[];for(var i=0;i<32;i++){c_cc.push((growMemViews(),HEAP8)[argp+i+17])}return stream.tty.ops.ioctl_tcsets(stream.tty,op,{c_iflag,c_oflag,c_cflag,c_lflag,c_cc})}return 0}case 21519:{if(!stream.tty)return-59;var argp=syscallGetVarargP();(growMemViews(),HEAP32)[argp>>2]=0;return 0}case 21520:{if(!stream.tty)return-59;return-28}case 21537:case 21531:{var argp=syscallGetVarargP();return FS.ioctl(stream,op,argp)}case 21523:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tiocgwinsz){var winsize=stream.tty.ops.ioctl_tiocgwinsz(stream.tty);var argp=syscallGetVarargP();(growMemViews(),HEAP16)[argp>>1]=winsize[0];(growMemViews(),HEAP16)[argp+2>>1]=winsize[1]}return 0}case 21524:{if(!stream.tty)return-59;return 0}case 21515:{if(!stream.tty)return-59;return 0}default:return-28}}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_lstat64(path,buf){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(10,0,1,path,buf);try{path=SYSCALLS.getStr(path);return SYSCALLS.writeStat(buf,FS.lstat(path))}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_newfstatat(dirfd,path,buf,flags){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(11,0,1,dirfd,path,buf,flags);try{path=SYSCALLS.getStr(path);var nofollow=flags&256;var allowEmpty=flags&4096;flags=flags&~6400;path=SYSCALLS.calculateAt(dirfd,path,allowEmpty);return SYSCALLS.writeStat(buf,nofollow?FS.lstat(path):FS.stat(path))}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_openat(dirfd,path,flags,varargs){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(12,0,1,dirfd,path,flags,varargs);SYSCALLS.varargs=varargs;try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);var mode=varargs?syscallGetVarargI():0;if(flags&64){mode&=~SYSCALLS.currentUmask}return FS.open(path,flags,mode).fd}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var doPoll=(fds,nfds,timeout,makeNotifyCallback)=>{var count=0;for(var i=0;i>2];var events=(growMemViews(),HEAP16)[pollfd+4>>1];var flags=32;var stream=FS.getStream(fd);if(stream){if(stream.stream_ops.poll){flags=timeout?stream.stream_ops.poll(stream,timeout,makeNotifyCallback(stream,pollfd)):stream.stream_ops.poll(stream,-1)}else{flags=5}}flags&=events|8|16;if(flags)count++;(growMemViews(),HEAP16)[pollfd+6>>1]=flags}return count};var ___syscall_poll=function(fds,nfds,timeout){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(13,0,2,fds,nfds,timeout);try{const isAsyncContext=PThread.currentProxiedOperationCallerThread;var resolve;var promise=new Promise(resolve_=>{resolve=resolve_});var cleanupFuncs=[];var notifyDone=false;function asyncPollComplete(count){if(notifyDone){return}notifyDone=true;cleanupFuncs.forEach(cb=>cb());resolve(count)}function makeNotifyCallback(stream,pollfd){var cb=flags=>{if(notifyDone){return}var events=(growMemViews(),HEAP16)[pollfd+4>>1];flags&=events|8|16;(growMemViews(),HEAP16)[pollfd+6>>1]=flags;asyncPollComplete(1)};cb.registerCleanupFunc=f=>{if(f)cleanupFuncs.push(f)};return cb}if(isAsyncContext){if(timeout>0){var t=setTimeout(()=>{asyncPollComplete(0)},timeout);cleanupFuncs.push(()=>clearTimeout(t))}var count=doPoll(fds,nfds,timeout,makeNotifyCallback);if(count||!timeout){asyncPollComplete(count)}return promise}var count=doPoll(fds,nfds,0,undefined);return count}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}};function ___syscall_poll_nonblocking(fds,nfds){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(14,0,1,fds,nfds);try{return doPoll(fds,nfds,0,undefined)}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_rmdir(path){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(15,0,1,path);try{path=SYSCALLS.getStr(path);FS.rmdir(path);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_stat64(path,buf){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(16,0,1,path,buf);try{path=SYSCALLS.getStr(path);return SYSCALLS.writeStat(buf,FS.stat(path))}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_unlinkat(dirfd,path,flags){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(17,0,1,dirfd,path,flags);try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);if(!flags){FS.unlink(path)}else if(flags===512){FS.rmdir(path)}else{return-28}return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var __abort_js=()=>abort("");var emnapiCtx=undefined;function __emnapi_callback_into_module(forceUncaught,env,callback,data,close_scope_if_throw){var envObject=emnapiCtx.envStore.get(env);var scope=emnapiCtx.openScope(envObject);try{envObject.callbackIntoModule(Boolean(forceUncaught),function(){getWasmTableEntry(callback)(env,data)})}catch(err){emnapiCtx.closeScope(envObject,scope);if(close_scope_if_throw){emnapiCtx.closeScope(envObject)}throw err}emnapiCtx.closeScope(envObject,scope)}function __emnapi_ctx_decrease_waiting_request_counter(){emnapiCtx.decreaseWaitingRequestCounter()}function __emnapi_ctx_increase_waiting_request_counter(){emnapiCtx.increaseWaitingRequestCounter()}function __emnapi_env_check_gc_access(env){var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess()}function __emnapi_get_last_error_info(env,error_code,engine_error_code,engine_reserved){var envObject=emnapiCtx.envStore.get(env);var lastError=envObject.lastError;var errorCode=lastError.errorCode;var engineErrorCode=lastError.engineErrorCode>>>0;var engineReserved=lastError.engineReserved;(growMemViews(),HEAP32)[error_code>>2]=errorCode;(growMemViews(),HEAPU32)[engine_error_code>>2]=engineErrorCode;(growMemViews(),HEAPU32)[engine_reserved>>2]=engineReserved}var emnapiNodeBinding=undefined;function __emnapi_node_emit_async_destroy(async_id,trigger_async_id){if(!emnapiNodeBinding)return;emnapiNodeBinding.node.emitAsyncDestroy({asyncId:async_id,triggerAsyncId:trigger_async_id})}function __emnapi_node_emit_async_init(async_resource,async_resource_name,trigger_async_id,result){if(!emnapiNodeBinding)return;var resource=emnapiCtx.handleStore.get(async_resource).value;var resource_name=emnapiCtx.handleStore.get(async_resource_name).value;var asyncContext=emnapiNodeBinding.node.emitAsyncInit(resource,resource_name,trigger_async_id);var asyncId=asyncContext.asyncId;var triggerAsyncId=asyncContext.triggerAsyncId;if(result){(growMemViews(),HEAPF64)[result>>3]=asyncId;(growMemViews(),HEAPF64)[result+8>>3]=triggerAsyncId}}function __emnapi_node_make_callback(env,async_resource,cb,argv,size,async_id,trigger_async_id,result){var i=0;var v;if(!emnapiNodeBinding)return;var resource=emnapiCtx.handleStore.get(async_resource).value;var callback=emnapiCtx.handleStore.get(cb).value;size=size>>>0;var arr=Array(size);for(;i>2];arr[i]=emnapiCtx.handleStore.get(argVal).value}var ret=emnapiNodeBinding.node.makeCallback(resource,callback,arr,{asyncId:async_id,triggerAsyncId:trigger_async_id});if(result){var envObject=emnapiCtx.envStore.get(env);v=envObject.ensureHandleId(ret);(growMemViews(),HEAPU32)[result>>2]=v}}function __emnapi_set_immediate(callback,data){emnapiCtx.feature.setImmediate(function(){getWasmTableEntry(callback)(data)})}function __emnapi_worker_unref(pid){var worker=PThread.pthreads[pid];worker=worker.worker||worker;if(typeof worker.unref==="function"){worker.unref()}}var __emscripten_init_main_thread_js=tb=>{var can_block=!ENVIRONMENT_IS_WEB;__emscripten_thread_init(tb,!ENVIRONMENT_IS_WORKER,1,can_block,65536,false);PThread.threadInitTLS()};var handleException=e=>{if(e instanceof ExitStatus||e=="unwind"){return EXITSTATUS}quit_(1,e)};var maybeExit=()=>{if(!keepRuntimeAlive()){try{if(ENVIRONMENT_IS_PTHREAD){if(_pthread_self())__emscripten_thread_exit(EXITSTATUS);return}_exit(EXITSTATUS)}catch(e){handleException(e)}}};var callUserCallback=func=>{if(ABORT){return}try{return func()}catch(e){handleException(e)}finally{maybeExit()}};var __emscripten_thread_mailbox_await=pthread_ptr=>{if(!waitAsyncPolyfilled){var wait=Atomics.waitAsync((growMemViews(),HEAP32),pthread_ptr>>2,pthread_ptr);wait.value.then(checkMailbox);var waitingAsync=pthread_ptr+112;Atomics.store((growMemViews(),HEAP32),waitingAsync>>2,1)}};var checkMailbox=()=>{var pthread_ptr=_pthread_self();if(!pthread_ptr)return;callUserCallback(()=>{__emscripten_thread_mailbox_await(pthread_ptr);__emscripten_check_mailbox()})};var __emscripten_notify_mailbox_postmessage=(targetThread,currThreadId)=>{if(targetThread==currThreadId){setTimeout(checkMailbox)}else if(ENVIRONMENT_IS_PTHREAD){postMessage({targetThread,cmd:4})}else{var worker=PThread.pthreads[targetThread];if(!worker){return}worker.postMessage({cmd:4})}};var proxiedJSCallArgs=[];var __emscripten_receive_on_main_thread_js=(funcIndex,emAsmAddr,callingThread,bufSize,args,ctx,ctxArgs)=>{proxiedJSCallArgs.length=0;var b=args>>3;var end=args+bufSize>>3;while(b__emscripten_run_js_on_main_thread_done(ctx,ctxArgs,rtn));return}return rtn};var __emscripten_runtime_keepalive_clear=()=>{noExitRuntime=false;runtimeKeepaliveCounter=0};var __emscripten_thread_cleanup=thread=>{if(!ENVIRONMENT_IS_PTHREAD)cleanupThread(thread);else postMessage({cmd:6,thread})};var __emscripten_thread_set_strongref=thread=>{if(ENVIRONMENT_IS_NODE){var worker=PThread.pthreads[thread];worker.ref();worker.strongref=1}};function __gmtime_js(time,tmPtr){time=bigintToI53Checked(time);var date=new Date(time*1e3);(growMemViews(),HEAP32)[tmPtr>>2]=date.getUTCSeconds();(growMemViews(),HEAP32)[tmPtr+4>>2]=date.getUTCMinutes();(growMemViews(),HEAP32)[tmPtr+8>>2]=date.getUTCHours();(growMemViews(),HEAP32)[tmPtr+12>>2]=date.getUTCDate();(growMemViews(),HEAP32)[tmPtr+16>>2]=date.getUTCMonth();(growMemViews(),HEAP32)[tmPtr+20>>2]=date.getUTCFullYear()-1900;(growMemViews(),HEAP32)[tmPtr+24>>2]=date.getUTCDay();var start=Date.UTC(date.getUTCFullYear(),0,1,0,0,0,0);var yday=(date.getTime()-start)/(1e3*60*60*24)|0;(growMemViews(),HEAP32)[tmPtr+28>>2]=yday}var isLeapYear=year=>year%4===0&&(year%100!==0||year%400===0);var MONTH_DAYS_LEAP_CUMULATIVE=[0,31,60,91,121,152,182,213,244,274,305,335];var MONTH_DAYS_REGULAR_CUMULATIVE=[0,31,59,90,120,151,181,212,243,273,304,334];var ydayFromDate=date=>{var leap=isLeapYear(date.getFullYear());var monthDaysCumulative=leap?MONTH_DAYS_LEAP_CUMULATIVE:MONTH_DAYS_REGULAR_CUMULATIVE;var yday=monthDaysCumulative[date.getMonth()]+date.getDate()-1;return yday};function __localtime_js(time,tmPtr){time=bigintToI53Checked(time);var date=new Date(time*1e3);(growMemViews(),HEAP32)[tmPtr>>2]=date.getSeconds();(growMemViews(),HEAP32)[tmPtr+4>>2]=date.getMinutes();(growMemViews(),HEAP32)[tmPtr+8>>2]=date.getHours();(growMemViews(),HEAP32)[tmPtr+12>>2]=date.getDate();(growMemViews(),HEAP32)[tmPtr+16>>2]=date.getMonth();(growMemViews(),HEAP32)[tmPtr+20>>2]=date.getFullYear()-1900;(growMemViews(),HEAP32)[tmPtr+24>>2]=date.getDay();var yday=ydayFromDate(date)|0;(growMemViews(),HEAP32)[tmPtr+28>>2]=yday;(growMemViews(),HEAP32)[tmPtr+36>>2]=-(date.getTimezoneOffset()*60);var start=new Date(date.getFullYear(),0,1);var summerOffset=new Date(date.getFullYear(),6,1).getTimezoneOffset();var winterOffset=start.getTimezoneOffset();var dst=(summerOffset!=winterOffset&&date.getTimezoneOffset()==Math.min(winterOffset,summerOffset))|0;(growMemViews(),HEAP32)[tmPtr+32>>2]=dst}function __mmap_js(len,prot,flags,fd,offset,allocated,addr){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(18,0,1,len,prot,flags,fd,offset,allocated,addr);offset=bigintToI53Checked(offset);try{var stream=SYSCALLS.getStreamFromFD(fd);var res=FS.mmap(stream,len,offset,prot,flags);var ptr=res.ptr;(growMemViews(),HEAP32)[allocated>>2]=res.allocated;(growMemViews(),HEAPU32)[addr>>2]=ptr;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function __munmap_js(addr,len,prot,flags,fd,offset){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(19,0,1,addr,len,prot,flags,fd,offset);offset=bigintToI53Checked(offset);try{var stream=SYSCALLS.getStreamFromFD(fd);if(prot&2){SYSCALLS.doMsync(addr,stream,len,flags,offset)}}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var __tzset_js=(timezone,daylight,std_name,dst_name)=>{var currentYear=(new Date).getFullYear();var winter=new Date(currentYear,0,1);var summer=new Date(currentYear,6,1);var winterOffset=winter.getTimezoneOffset();var summerOffset=summer.getTimezoneOffset();var stdTimezoneOffset=Math.max(winterOffset,summerOffset);(growMemViews(),HEAPU32)[timezone>>2]=stdTimezoneOffset*60;(growMemViews(),HEAP32)[daylight>>2]=Number(winterOffset!=summerOffset);var extractZone=timezoneOffset=>{var sign=timezoneOffset>=0?"-":"+";var absOffset=Math.abs(timezoneOffset);var hours=String(Math.floor(absOffset/60)).padStart(2,"0");var minutes=String(absOffset%60).padStart(2,"0");return`UTC${sign}${hours}${minutes}`};var winterName=extractZone(winterOffset);var summerName=extractZone(summerOffset);if(summerOffsetperformance.timeOrigin+performance.now();var _emscripten_date_now=()=>Date.now();var nowIsMonotonic=1;var checkWasiClock=clock_id=>clock_id>=0&&clock_id<=3;function _clock_time_get(clk_id,ignored_precision,ptime){ignored_precision=bigintToI53Checked(ignored_precision);if(!checkWasiClock(clk_id)){return 28}var now;if(clk_id===0){now=_emscripten_date_now()}else if(nowIsMonotonic){now=_emscripten_get_now()}else{return 52}var nsec=Math.round(now*1e3*1e3);(growMemViews(),HEAP64)[ptime>>3]=BigInt(nsec);return 0}function _emnapi_is_node_binding_available(){return emnapiNodeBinding?1:0}var _emscripten_check_blocking_allowed=()=>{};var runtimeKeepalivePush=()=>{runtimeKeepaliveCounter+=1};var _emscripten_exit_with_live_runtime=()=>{runtimeKeepalivePush();throw"unwind"};var getHeapMax=()=>2147483648;var _emscripten_get_heap_max=()=>getHeapMax();var _emscripten_num_logical_cores=()=>ENVIRONMENT_IS_NODE?require("node:os").cpus().length:navigator["hardwareConcurrency"];var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=(growMemViews(),HEAPU8).length;requestedSize>>>=0;if(requestedSize<=oldSize){return false}var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};var runtimeKeepalivePop=()=>{runtimeKeepaliveCounter-=1};var _emscripten_runtime_keepalive_pop=runtimeKeepalivePop;var _emscripten_runtime_keepalive_push=runtimeKeepalivePush;var ENV={};var getExecutableName=()=>thisProgram;var getEnvStrings=()=>{if(!getEnvStrings.strings){var lang=(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8";var env={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:lang,_:getExecutableName()};if(ENVIRONMENT_IS_NODE){env=process.env}for(var x in ENV){if(ENV[x]===undefined)delete env[x];else env[x]=ENV[x]}var strings=[];for(var x in env){strings.push(`${x}=${env[x]}`)}getEnvStrings.strings=strings}return getEnvStrings.strings};function _environ_get(__environ,environ_buf){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(20,0,1,__environ,environ_buf);var bufSize=0;var envp=0;for(var string of getEnvStrings()){var ptr=environ_buf+bufSize;(growMemViews(),HEAPU32)[__environ+envp>>2]=ptr;bufSize+=stringToUTF8(string,ptr,Infinity)+1;envp+=4}return 0}function _environ_sizes_get(penviron_count,penviron_buf_size){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(21,0,1,penviron_count,penviron_buf_size);var strings=getEnvStrings();(growMemViews(),HEAPU32)[penviron_count>>2]=strings.length;var bufSize=0;for(var string of strings){bufSize+=lengthBytesUTF8(string)+1}(growMemViews(),HEAPU32)[penviron_buf_size>>2]=bufSize;return 0}function _fd_close(fd){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(22,0,1,fd);try{var stream=SYSCALLS.getStreamFromFD(fd);FS.close(stream);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}function _fd_fdstat_get(fd,pbuf){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(23,0,1,fd,pbuf);try{var rightsBase=0;var rightsInheriting=0;var flags=0;{var stream=SYSCALLS.getStreamFromFD(fd);var type=stream.tty?2:FS.isDir(stream.mode)?3:FS.isLink(stream.mode)?7:4}(growMemViews(),HEAP8)[pbuf]=type;(growMemViews(),HEAP16)[pbuf+2>>1]=flags;(growMemViews(),HEAP64)[pbuf+8>>3]=BigInt(rightsBase);(growMemViews(),HEAP64)[pbuf+16>>3]=BigInt(rightsInheriting);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doReadv=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i>2];var len=(growMemViews(),HEAPU32)[iov+4>>2];iov+=8;var curr=FS.read(stream,(growMemViews(),HEAP8),ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}function _fd_seek(fd,offset,whence,newOffset){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(25,0,1,fd,offset,whence,newOffset);offset=bigintToI53Checked(offset);try{if(isNaN(offset))return 22;var stream=SYSCALLS.getStreamFromFD(fd);FS.llseek(stream,offset,whence);(growMemViews(),HEAP64)[newOffset>>3]=BigInt(stream.position);if(stream.getdents&&offset===0&&whence===0)stream.getdents=null;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doWritev=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i>2];var len=(growMemViews(),HEAPU32)[iov+4>>2];iov+=8;var curr=FS.write(stream,(growMemViews(),HEAP8),ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var emnapiExternalMemory={registry:{},table:new WeakMap,wasmMemoryViewTable:new WeakMap,init:function(){emnapiExternalMemory.registry=typeof FinalizationRegistry==="function"?new FinalizationRegistry(function(_pointer){_free(_pointer)}):undefined;emnapiExternalMemory.table=new WeakMap;emnapiExternalMemory.wasmMemoryViewTable=new WeakMap},isSharedArrayBuffer:function(value){return typeof SharedArrayBuffer==="function"&&value instanceof SharedArrayBuffer||Object.prototype.toString.call(value)==="[object SharedArrayBuffer]"},isDetachedArrayBuffer:function(arrayBuffer){if(arrayBuffer.byteLength===0){try{}catch(_){return true}}return false},getArrayBufferPointer:function(arrayBuffer,shouldCopy){var _a;var info={address:0,ownership:0,runtimeAllocated:0};if(arrayBuffer===wasmMemory.buffer){return info}var isDetached=emnapiExternalMemory.isDetachedArrayBuffer(arrayBuffer);if(emnapiExternalMemory.table.has(arrayBuffer)){var cachedInfo=emnapiExternalMemory.table.get(arrayBuffer);if(isDetached){cachedInfo.address=0;return cachedInfo}if(shouldCopy&&cachedInfo.ownership===0&&cachedInfo.runtimeAllocated===1){new Uint8Array(wasmMemory.buffer).set(new Uint8Array(arrayBuffer),cachedInfo.address)}return cachedInfo}if(isDetached||arrayBuffer.byteLength===0){return info}if(!shouldCopy){return info}var pointer=_malloc(arrayBuffer.byteLength);if(!pointer)throw new Error("Out of memory");new Uint8Array(wasmMemory.buffer).set(new Uint8Array(arrayBuffer),pointer);info.address=pointer;info.ownership=emnapiExternalMemory.registry?0:1;info.runtimeAllocated=1;emnapiExternalMemory.table.set(arrayBuffer,info);(_a=emnapiExternalMemory.registry)===null||_a===void 0?void 0:_a.register(arrayBuffer,pointer);return info},getOrUpdateMemoryView:function(view){if(view.buffer===wasmMemory.buffer){if(!emnapiExternalMemory.wasmMemoryViewTable.has(view)){emnapiExternalMemory.wasmMemoryViewTable.set(view,{Ctor:view.constructor,address:view.byteOffset,length:view instanceof DataView?view.byteLength:view.length,ownership:1,runtimeAllocated:0})}return view}var maybeOldWasmMemory=emnapiExternalMemory.isDetachedArrayBuffer(view.buffer)||emnapiExternalMemory.isSharedArrayBuffer(view.buffer);if(maybeOldWasmMemory&&emnapiExternalMemory.wasmMemoryViewTable.has(view)){var info=emnapiExternalMemory.wasmMemoryViewTable.get(view);var Ctor=info.Ctor;var newView=void 0;var Buffer=emnapiCtx.feature.Buffer;if(typeof Buffer==="function"&&Ctor===Buffer){newView=Buffer.from(wasmMemory.buffer,info.address,info.length)}else{newView=new Ctor(wasmMemory.buffer,info.address,info.length)}emnapiExternalMemory.wasmMemoryViewTable.set(newView,info);return newView}return view},getViewPointer:function(view,shouldCopy){view=emnapiExternalMemory.getOrUpdateMemoryView(view);if(view.buffer===wasmMemory.buffer){if(emnapiExternalMemory.wasmMemoryViewTable.has(view)){var _a=emnapiExternalMemory.wasmMemoryViewTable.get(view),address_1=_a.address,ownership_1=_a.ownership,runtimeAllocated_1=_a.runtimeAllocated;return{address:address_1,ownership:ownership_1,runtimeAllocated:runtimeAllocated_1,view}}return{address:view.byteOffset,ownership:1,runtimeAllocated:0,view}}var _b=emnapiExternalMemory.getArrayBufferPointer(view.buffer,shouldCopy),address=_b.address,ownership=_b.ownership,runtimeAllocated=_b.runtimeAllocated;return{address:address===0?0:address+view.byteOffset,ownership,runtimeAllocated,view}}};function emnapiGetHandle(js_object){var handle=emnapiCtx.handleStore.get(js_object);if(!(handle.isObject()||handle.isFunction())){return{status:1}}if(typeof emnapiExternalMemory!=="undefined"&&ArrayBuffer.isView(handle.value)){if(emnapiExternalMemory.wasmMemoryViewTable.has(handle.value)){handle=emnapiCtx.addToCurrentScope(emnapiExternalMemory.wasmMemoryViewTable.get(handle.value))}}return{status:0,handle}}function _napi_add_finalizer(env,js_object,finalize_data,finalize_cb,finalize_hint,result){if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!emnapiCtx.feature.supportFinalizer){return envObject.setLastError(9)}if(!js_object)return envObject.setLastError(1);if(!finalize_cb)return envObject.setLastError(1);var handleResult=emnapiGetHandle(js_object);if(handleResult.status!==0){return envObject.setLastError(handleResult.status)}var handle=handleResult.handle;var ownership=!result?0:1;var reference=emnapiCtx.createReferenceWithFinalizer(envObject,handle.id,0,ownership,finalize_cb,finalize_data,finalize_hint);if(result){var referenceId=reference.id;(growMemViews(),HEAPU32)[result>>2]=referenceId}return envObject.clearLastError()}function _napi_call_function(env,recv,func,argc,argv,result){var i=0;var v;if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!envObject.tryCatch.isEmpty())return envObject.setLastError(10);if(!envObject.canCallIntoJs())return envObject.setLastError(envObject.moduleApiVersion>=10?23:10);envObject.clearLastError();try{if(!recv)return envObject.setLastError(1);argc=argc>>>0;if(argc>0){if(!argv)return envObject.setLastError(1)}var v8recv=emnapiCtx.handleStore.get(recv).value;if(!func)return envObject.setLastError(1);var v8func=emnapiCtx.handleStore.get(func).value;if(typeof v8func!=="function")return envObject.setLastError(1);var args=[];for(;i>2];args.push(emnapiCtx.handleStore.get(argVal).value)}var ret=v8func.apply(v8recv,args);if(result){v=envObject.ensureHandleId(ret);(growMemViews(),HEAPU32)[result>>2]=v}return envObject.clearLastError()}catch(err){envObject.tryCatch.setError(err);return envObject.setLastError(10)}}function _napi_clear_last_error(env){var envObject=emnapiCtx.envStore.get(env);return envObject.clearLastError()}function _napi_close_escapable_handle_scope(env,scope){if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!scope)return envObject.setLastError(1);if(envObject.openHandleScopes===0){return 13}emnapiCtx.closeScope(envObject);return envObject.clearLastError()}function _napi_close_handle_scope(env,scope){if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!scope)return envObject.setLastError(1);if(envObject.openHandleScopes===0){return 13}emnapiCtx.closeScope(envObject);return envObject.clearLastError()}function _napi_coerce_to_object(env,value,result){var v;if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!envObject.tryCatch.isEmpty())return envObject.setLastError(10);if(!envObject.canCallIntoJs())return envObject.setLastError(envObject.moduleApiVersion>=10?23:10);envObject.clearLastError();try{if(!value)return envObject.setLastError(1);if(!result)return envObject.setLastError(1);var handle=emnapiCtx.handleStore.get(value);if(handle.value==null){throw new TypeError("Cannot convert undefined or null to object")}v=envObject.ensureHandleId(Object(handle.value));(growMemViews(),HEAPU32)[result>>2]=v;return envObject.getReturnStatus()}catch(err){envObject.tryCatch.setError(err);return envObject.setLastError(10)}}function _napi_coerce_to_string(env,value,result){var v;if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!envObject.tryCatch.isEmpty())return envObject.setLastError(10);if(!envObject.canCallIntoJs())return envObject.setLastError(envObject.moduleApiVersion>=10?23:10);envObject.clearLastError();try{if(!value)return envObject.setLastError(1);if(!result)return envObject.setLastError(1);var handle=emnapiCtx.handleStore.get(value);if(handle.isSymbol()){throw new TypeError("Cannot convert a Symbol value to a string")}v=emnapiCtx.addToCurrentScope(String(handle.value)).id;(growMemViews(),HEAPU32)[result>>2]=v;return envObject.getReturnStatus()}catch(err){envObject.tryCatch.setError(err);return envObject.setLastError(10)}}function _napi_create_array(env,result){if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!result)return envObject.setLastError(1);var value=emnapiCtx.addToCurrentScope([]).id;(growMemViews(),HEAPU32)[result>>2]=value;return envObject.clearLastError()}function _napi_create_array_with_length(env,length,result){if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!result)return envObject.setLastError(1);length=length>>>0;var value=emnapiCtx.addToCurrentScope(new Array(length)).id;(growMemViews(),HEAPU32)[result>>2]=value;return envObject.clearLastError()}function emnapiCreateArrayBuffer(byte_length,data,shared){byte_length=byte_length>>>0;var arrayBuffer=shared?new SharedArrayBuffer(byte_length):new ArrayBuffer(byte_length);if(data){var p=emnapiExternalMemory.getArrayBufferPointer(arrayBuffer,true).address;(growMemViews(),HEAPU32)[data>>2]=p}return arrayBuffer}function _napi_create_buffer_copy(env,length,data,result_data,result){var value;if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!envObject.tryCatch.isEmpty())return envObject.setLastError(10);if(!envObject.canCallIntoJs())return envObject.setLastError(envObject.moduleApiVersion>=10?23:10);envObject.clearLastError();try{if(!result)return envObject.setLastError(1);var Buffer=emnapiCtx.feature.Buffer;if(!Buffer){throw emnapiCtx.createNotSupportBufferError("napi_create_buffer_copy","")}var arrayBuffer=emnapiCreateArrayBuffer(length,result_data,false);var buffer=Buffer.from(arrayBuffer);buffer.set(new Uint8Array(wasmMemory.buffer).subarray(data,data+length));value=emnapiCtx.addToCurrentScope(buffer).id;(growMemViews(),HEAPU32)[result>>2]=value;return envObject.getReturnStatus()}catch(err){envObject.tryCatch.setError(err);return envObject.setLastError(10)}}function _napi_create_double(env,value,result){if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!result)return envObject.setLastError(1);var v=emnapiCtx.addToCurrentScope(value).id;(growMemViews(),HEAPU32)[result>>2]=v;return envObject.clearLastError()}function _napi_create_error(env,code,msg,result){if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!msg)return envObject.setLastError(1);if(!result)return envObject.setLastError(1);var msgValue=emnapiCtx.handleStore.get(msg).value;if(typeof msgValue!=="string"){return envObject.setLastError(3)}var error=new Error(msgValue);if(code){var codeValue=emnapiCtx.handleStore.get(code).value;if(typeof codeValue!=="string"){return envObject.setLastError(3)}error.code=codeValue}var value=emnapiCtx.addToCurrentScope(error).id;(growMemViews(),HEAPU32)[result>>2]=value;return envObject.clearLastError()}function _emnapi_create_memory_view(env,typedarray_type,external_data,byte_length,finalize_cb,finalize_hint,result){var value;if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!envObject.tryCatch.isEmpty())return envObject.setLastError(10);if(!envObject.canCallIntoJs())return envObject.setLastError(envObject.moduleApiVersion>=10?23:10);envObject.clearLastError();try{if(!result)return envObject.setLastError(1);byte_length=byte_length>>>0;if(!external_data){byte_length=0}if(byte_length>2147483647){throw new RangeError("Cannot create a memory view larger than 2147483647 bytes")}if(external_data+byte_length>wasmMemory.buffer.byteLength){throw new RangeError("Memory out of range")}if(!emnapiCtx.feature.supportFinalizer&&finalize_cb){throw emnapiCtx.createNotSupportWeakRefError("emnapi_create_memory_view",'Parameter "finalize_cb" must be 0(NULL)')}var viewDescriptor=void 0;switch(typedarray_type){case 0:viewDescriptor={Ctor:Int8Array,address:external_data,length:byte_length,ownership:1,runtimeAllocated:0};break;case 1:viewDescriptor={Ctor:Uint8Array,address:external_data,length:byte_length,ownership:1,runtimeAllocated:0};break;case 2:viewDescriptor={Ctor:Uint8ClampedArray,address:external_data,length:byte_length,ownership:1,runtimeAllocated:0};break;case 3:viewDescriptor={Ctor:Int16Array,address:external_data,length:byte_length>>1,ownership:1,runtimeAllocated:0};break;case 4:viewDescriptor={Ctor:Uint16Array,address:external_data,length:byte_length>>1,ownership:1,runtimeAllocated:0};break;case 5:viewDescriptor={Ctor:Int32Array,address:external_data,length:byte_length>>2,ownership:1,runtimeAllocated:0};break;case 6:viewDescriptor={Ctor:Uint32Array,address:external_data,length:byte_length>>2,ownership:1,runtimeAllocated:0};break;case 7:viewDescriptor={Ctor:Float32Array,address:external_data,length:byte_length>>2,ownership:1,runtimeAllocated:0};break;case 8:viewDescriptor={Ctor:Float64Array,address:external_data,length:byte_length>>3,ownership:1,runtimeAllocated:0};break;case 9:viewDescriptor={Ctor:BigInt64Array,address:external_data,length:byte_length>>3,ownership:1,runtimeAllocated:0};break;case 10:viewDescriptor={Ctor:BigUint64Array,address:external_data,length:byte_length>>3,ownership:1,runtimeAllocated:0};break;case-1:viewDescriptor={Ctor:DataView,address:external_data,length:byte_length,ownership:1,runtimeAllocated:0};break;case 11:if(typeof Float16Array!=="function"){return envObject.setLastError(1)}viewDescriptor={Ctor:Float16Array,address:external_data,length:byte_length>>1,ownership:1,runtimeAllocated:0};break;case-2:{if(!emnapiCtx.feature.Buffer){throw emnapiCtx.createNotSupportBufferError("emnapi_create_memory_view","")}viewDescriptor={Ctor:emnapiCtx.feature.Buffer,address:external_data,length:byte_length,ownership:1,runtimeAllocated:0};break}default:return envObject.setLastError(1)}var Ctor=viewDescriptor.Ctor;var typedArray=typedarray_type===-2?emnapiCtx.feature.Buffer.from(wasmMemory.buffer,viewDescriptor.address,viewDescriptor.length):new Ctor(wasmMemory.buffer,viewDescriptor.address,viewDescriptor.length);var handle=emnapiCtx.addToCurrentScope(typedArray);emnapiExternalMemory.wasmMemoryViewTable.set(typedArray,viewDescriptor);if(finalize_cb){var status_1=_napi_add_finalizer(env,handle.id,external_data,finalize_cb,finalize_hint,0);if(status_1===10){var err=envObject.tryCatch.extractException();envObject.clearLastError();throw err}else if(status_1!==0){return envObject.setLastError(status_1)}}value=handle.id;(growMemViews(),HEAPU32)[result>>2]=value;return envObject.getReturnStatus()}catch(err){envObject.tryCatch.setError(err);return envObject.setLastError(10)}}function _napi_create_external_buffer(env,length,data,finalize_cb,finalize_hint,result){return _emnapi_create_memory_view(env,-2,data,length,finalize_cb,finalize_hint,result)}var emnapiString={utf8Decoder:undefined,utf16Decoder:undefined,init:function(){var utf8Decoder;utf8Decoder=new TextDecoder;emnapiString.utf8Decoder=utf8Decoder;var utf16Decoder;utf16Decoder=new TextDecoder("utf-16le");emnapiString.utf16Decoder=utf16Decoder},lengthBytesUTF8:function(str){var c;var len=0;for(var i=0;i=55296&&c<=57343){len+=4;++i}else{len+=3}}return len},UTF8ToString:function(ptr,length){if(!ptr||!length)return"";ptr>>>=0;var HEAPU8=new Uint8Array(wasmMemory.buffer);var end=ptr;if(length===-1||length===4294967295){for(;(growMemViews(),HEAPU8)[end];)++end}else{end=ptr+(length>>>0)}return emnapiString.utf8Decoder.decode((growMemViews(),HEAPU8).slice(ptr,end))},stringToUTF8:function(str,outPtr,maxBytesToWrite){var HEAPU8=new Uint8Array(wasmMemory.buffer);var outIdx=outPtr;outIdx>>>=0;if(!(maxBytesToWrite>0)){return 0}var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;(growMemViews(),HEAPU8)[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;(growMemViews(),HEAPU8)[outIdx++]=192|u>>6;(growMemViews(),HEAPU8)[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;(growMemViews(),HEAPU8)[outIdx++]=224|u>>12;(growMemViews(),HEAPU8)[outIdx++]=128|u>>6&63;(growMemViews(),HEAPU8)[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;(growMemViews(),HEAPU8)[outIdx++]=240|u>>18;(growMemViews(),HEAPU8)[outIdx++]=128|u>>12&63;(growMemViews(),HEAPU8)[outIdx++]=128|u>>6&63;(growMemViews(),HEAPU8)[outIdx++]=128|u&63}}(growMemViews(),HEAPU8)[outIdx]=0;return outIdx-startIdx},UTF16ToString:function(ptr,length){if(!ptr||!length)return"";ptr>>>=0;var end=ptr;if(length===-1||length===4294967295){var idx=end>>>1;var HEAPU16=new Uint16Array(wasmMemory.buffer);while((growMemViews(),HEAPU16)[idx])++idx;end=idx<<1>>>0}else{end=ptr+(length>>>0)*2}var HEAPU8=new Uint8Array(wasmMemory.buffer);return emnapiString.utf16Decoder.decode((growMemViews(),HEAPU8).slice(ptr,end))},stringToUTF16:function(str,outPtr,maxBytesToWrite){if(maxBytesToWrite===undefined){maxBytesToWrite=2147483647}if(maxBytesToWrite<2)return 0;maxBytesToWrite-=2;var startPtr=outPtr;var numCharsToWrite=maxBytesToWrite>1]=codeUnit;outPtr+=2}(growMemViews(),HEAP16)[outPtr>>1]=0;return outPtr-startPtr},newString:function(env,str,length,result,stringMaker){if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();var autoLength=length===-1||length===4294967295;var sizelength=length>>>0;if(length!==0){if(!str)return envObject.setLastError(1)}if(!result)return envObject.setLastError(1);if(!(autoLength||sizelength<=2147483647))return envObject.setLastError(1);var strValue=stringMaker(str,autoLength,sizelength);var value=emnapiCtx.addToCurrentScope(strValue).id;(growMemViews(),HEAPU32)[result>>2]=value;return envObject.clearLastError()},newExternalString:function(env,str,length,finalize_callback,finalize_hint,result,copied,createApi,stringMaker){if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();var autoLength=length===-1||length===4294967295;var sizelength=length>>>0;if(length!==0){if(!str)return envObject.setLastError(1)}if(!result)return envObject.setLastError(1);if(!(autoLength||sizelength<=2147483647))return envObject.setLastError(1);var status=createApi(env,str,length,result);if(status===0){if(copied){(growMemViews(),HEAP8)[copied]=1}if(finalize_callback){envObject.callFinalizer(finalize_callback,str,finalize_hint)}}return status}};function emnapiCreateFunction(envObject,utf8name,length,cb,data){var functionName=!utf8name||!length?"":emnapiString.UTF8ToString(utf8name,length);var f;var napiCallback=getWasmTableEntry(cb);var callback=function(envObject){return napiCallback(envObject.id,envObject.ctx.scopeStore.currentScope.id)};var makeFunction=function(envObject,callback){return function(){"use strict";var scope=envObject.ctx.openScope(envObject);var callbackInfo=scope.callbackInfo;callbackInfo.data=data;callbackInfo.args=arguments;callbackInfo.thiz=this;callbackInfo.fn=f;try{var napiValue=envObject.callIntoModule(callback);return!napiValue?undefined:envObject.ctx.handleStore.get(napiValue).value}finally{callbackInfo.data=0;callbackInfo.args=undefined;callbackInfo.thiz=undefined;callbackInfo.fn=undefined;envObject.ctx.closeScope(envObject,scope)}}};if(functionName===""){f=makeFunction(envObject,callback);return{status:0,f}}if(!/^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(functionName)){return{status:1,f:undefined}}if(emnapiCtx.feature.supportNewFunction){var _=makeFunction(envObject,callback);try{f=new Function("_","return function "+functionName+"(){"+'"use strict";'+"return _.apply(this,arguments);"+"};")(_)}catch(_err){f=makeFunction(envObject,callback);if(emnapiCtx.feature.canSetFunctionName)Object.defineProperty(f,"name",{value:functionName})}}else{f=makeFunction(envObject,callback);if(emnapiCtx.feature.canSetFunctionName)Object.defineProperty(f,"name",{value:functionName})}return{status:0,f}}function __emnapi_create_function(env,utf8name,length,cb,data,result){var envObject=emnapiCtx.envStore.get(env);var fresult=emnapiCreateFunction(envObject,utf8name,length,cb,data);if(fresult.status!==0)return envObject.setLastError(fresult.status);var f=fresult.f;var valueHandle=emnapiCtx.addToCurrentScope(f);var value=valueHandle.id;(growMemViews(),HEAPU32)[result>>2]=value;return envObject.getReturnStatus()}function _napi_create_function(env,utf8name,length,cb,data,result){if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!envObject.tryCatch.isEmpty())return envObject.setLastError(10);if(!envObject.canCallIntoJs())return envObject.setLastError(envObject.moduleApiVersion>=10?23:10);envObject.clearLastError();try{if(!result)return envObject.setLastError(1);if(!cb)return envObject.setLastError(1);return __emnapi_create_function(env,utf8name,length,cb,data,result)}catch(err){envObject.tryCatch.setError(err);return envObject.setLastError(10)}}function _napi_create_object(env,result){if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!result)return envObject.setLastError(1);var value=emnapiCtx.addToCurrentScope({}).id;(growMemViews(),HEAPU32)[result>>2]=value;return envObject.clearLastError()}function _napi_create_reference(env,value,initial_refcount,result){if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!value)return envObject.setLastError(1);if(!result)return envObject.setLastError(1);var handle=emnapiCtx.handleStore.get(value);if(envObject.moduleApiVersion<10){if(!(handle.isObject()||handle.isFunction()||handle.isSymbol())){return envObject.setLastError(1)}}var ref=emnapiCtx.createReference(envObject,handle.id,initial_refcount>>>0,1);(growMemViews(),HEAPU32)[result>>2]=ref.id;return envObject.clearLastError()}function _napi_create_string_latin1(env,str,length,result){return emnapiString.newString(env,str,length,result,function(str,autoLength,sizeLength){var latin1String="";var len=0;if(autoLength){while(true){var ch=(growMemViews(),HEAPU8)[str];if(!ch)break;latin1String+=String.fromCharCode(ch);str++}}else{while(len>2]=value;return envObject.clearLastError()}function emnapiDefineProperty(envObject,obj,propertyName,method,getter,setter,value,attributes,data){if(getter||setter){var localGetter=void 0;var localSetter=void 0;if(getter){localGetter=emnapiCreateFunction(envObject,0,0,getter,data).f}if(setter){localSetter=emnapiCreateFunction(envObject,0,0,setter,data).f}var desc={configurable:(attributes&4)!==0,enumerable:(attributes&2)!==0,get:localGetter,set:localSetter};Object.defineProperty(obj,propertyName,desc)}else if(method){var localMethod=emnapiCreateFunction(envObject,0,0,method,data).f;var desc={configurable:(attributes&4)!==0,enumerable:(attributes&2)!==0,writable:(attributes&1)!==0,value:localMethod};Object.defineProperty(obj,propertyName,desc)}else{var desc={configurable:(attributes&4)!==0,enumerable:(attributes&2)!==0,writable:(attributes&1)!==0,value:emnapiCtx.handleStore.get(value).value};Object.defineProperty(obj,propertyName,desc)}}function _napi_define_properties(env,object,property_count,properties){var propPtr,attributes;if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!envObject.tryCatch.isEmpty())return envObject.setLastError(10);if(!envObject.canCallIntoJs())return envObject.setLastError(envObject.moduleApiVersion>=10?23:10);envObject.clearLastError();try{property_count=property_count>>>0;if(property_count>0){if(!properties)return envObject.setLastError(1)}if(!object)return envObject.setLastError(1);var h=emnapiCtx.handleStore.get(object);var maybeObject=h.value;if(!(h.isObject()||h.isFunction())){return envObject.setLastError(2)}var propertyName=void 0;for(var i=0;i>2];var name_2=(growMemViews(),HEAPU32)[propPtr+4>>2];var method=(growMemViews(),HEAPU32)[propPtr+8>>2];var getter=(growMemViews(),HEAPU32)[propPtr+12>>2];var setter=(growMemViews(),HEAPU32)[propPtr+16>>2];var value=(growMemViews(),HEAPU32)[propPtr+20>>2];attributes=(growMemViews(),HEAP32)[propPtr+24>>2];var data=(growMemViews(),HEAPU32)[propPtr+28>>2];if(utf8Name){propertyName=emnapiString.UTF8ToString(utf8Name,-1)}else{if(!name_2){return envObject.setLastError(4)}propertyName=emnapiCtx.handleStore.get(name_2).value;if(typeof propertyName!=="string"&&typeof propertyName!=="symbol"){return envObject.setLastError(4)}}emnapiDefineProperty(envObject,maybeObject,propertyName,method,getter,setter,value,attributes,data)}return envObject.getReturnStatus()}catch(err){envObject.tryCatch.setError(err);return envObject.setLastError(10)}}function _napi_delete_reference(env,ref){if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);if(!ref)return envObject.setLastError(1);emnapiCtx.refStore.get(ref).dispose();return envObject.clearLastError()}function _napi_escape_handle(env,scope,escapee,result){if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!scope)return envObject.setLastError(1);if(!escapee)return envObject.setLastError(1);if(!result)return envObject.setLastError(1);var scopeObject=emnapiCtx.scopeStore.get(scope);if(!scopeObject.escapeCalled()){var newHandle=scopeObject.escape(escapee);var value=newHandle?newHandle.id:0;(growMemViews(),HEAPU32)[result>>2]=value;return envObject.clearLastError()}return envObject.setLastError(12)}function _napi_fatal_error(location,location_len,message,message_len){var locationStr=emnapiString.UTF8ToString(location,location_len);var messageStr=emnapiString.UTF8ToString(message,message_len);if(emnapiNodeBinding){emnapiNodeBinding.napi.fatalError(locationStr,messageStr)}else{abort("FATAL ERROR: "+locationStr+" "+messageStr)}}function _napi_get_and_clear_last_exception(env,result){if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!result)return envObject.setLastError(1);if(!envObject.tryCatch.hasCaught()){(growMemViews(),HEAPU32)[result>>2]=1;return envObject.clearLastError()}else{var err=envObject.tryCatch.exception();var value=envObject.ensureHandleId(err);(growMemViews(),HEAPU32)[result>>2]=value;envObject.tryCatch.reset()}return envObject.clearLastError()}function _napi_get_array_length(env,value,result){if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!envObject.tryCatch.isEmpty())return envObject.setLastError(10);if(!envObject.canCallIntoJs())return envObject.setLastError(envObject.moduleApiVersion>=10?23:10);envObject.clearLastError();try{if(!value)return envObject.setLastError(1);if(!result)return envObject.setLastError(1);var handle=emnapiCtx.handleStore.get(value);if(!handle.isArray()){return envObject.setLastError(8)}var v=handle.value.length>>>0;(growMemViews(),HEAPU32)[result>>2]=v;return envObject.getReturnStatus()}catch(err){envObject.tryCatch.setError(err);return envObject.setLastError(10)}}function _napi_get_boolean(env,value,result){if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!result)return envObject.setLastError(1);var v=value===0?3:4;(growMemViews(),HEAPU32)[result>>2]=v;return envObject.clearLastError()}function _napi_get_cb_info(env,cbinfo,argc,argv,this_arg,data){if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);if(!cbinfo)return envObject.setLastError(1);var cbinfoValue=emnapiCtx.scopeStore.get(cbinfo).callbackInfo;if(argv){if(!argc)return envObject.setLastError(1);var argcValue=(growMemViews(),HEAPU32)[argc>>2];var len=cbinfoValue.args.length;var arrlen=argcValue>2]=argVal}if(i>2]=1}}}if(argc){(growMemViews(),HEAPU32)[argc>>2]=cbinfoValue.args.length}if(this_arg){var v=envObject.ensureHandleId(cbinfoValue.thiz);(growMemViews(),HEAPU32)[this_arg>>2]=v}if(data){(growMemViews(),HEAPU32)[data>>2]=cbinfoValue.data}return envObject.clearLastError()}function _napi_get_element(env,object,index,result){var value;if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!envObject.tryCatch.isEmpty())return envObject.setLastError(10);if(!envObject.canCallIntoJs())return envObject.setLastError(envObject.moduleApiVersion>=10?23:10);envObject.clearLastError();try{if(!result)return envObject.setLastError(1);if(!object)return envObject.setLastError(1);var h=emnapiCtx.handleStore.get(object);if(h.value==null){throw new TypeError("Cannot convert undefined or null to object")}var v=void 0;try{v=h.isObject()||h.isFunction()?h.value:Object(h.value)}catch(_){return envObject.setLastError(2)}value=envObject.ensureHandleId(v[index>>>0]);(growMemViews(),HEAPU32)[result>>2]=value;return envObject.getReturnStatus()}catch(err){envObject.tryCatch.setError(err);return envObject.setLastError(10)}}function _napi_get_named_property(env,object,utf8name,result){var value;if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!envObject.tryCatch.isEmpty())return envObject.setLastError(10);if(!envObject.canCallIntoJs())return envObject.setLastError(envObject.moduleApiVersion>=10?23:10);envObject.clearLastError();try{if(!result)return envObject.setLastError(1);if(!object)return envObject.setLastError(1);if(!utf8name){return envObject.setLastError(1)}var h=emnapiCtx.handleStore.get(object);if(h.value==null){throw new TypeError("Cannot convert undefined or null to object")}var v=void 0;try{v=h.isObject()||h.isFunction()?h.value:Object(h.value)}catch(_){return envObject.setLastError(2)}value=envObject.ensureHandleId(v[emnapiString.UTF8ToString(utf8name,-1)]);(growMemViews(),HEAPU32)[result>>2]=value;return envObject.getReturnStatus()}catch(err){envObject.tryCatch.setError(err);return envObject.setLastError(10)}}function _napi_get_null(env,result){if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!result)return envObject.setLastError(1);var value=2;(growMemViews(),HEAPU32)[result>>2]=value;return envObject.clearLastError()}function _napi_get_property(env,object,key,result){var value;if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!envObject.tryCatch.isEmpty())return envObject.setLastError(10);if(!envObject.canCallIntoJs())return envObject.setLastError(envObject.moduleApiVersion>=10?23:10);envObject.clearLastError();try{if(!key)return envObject.setLastError(1);if(!result)return envObject.setLastError(1);if(!object)return envObject.setLastError(1);var h=emnapiCtx.handleStore.get(object);if(h.value==null){throw new TypeError("Cannot convert undefined or null to object")}var v=void 0;try{v=h.isObject()||h.isFunction()?h.value:Object(h.value)}catch(_){return envObject.setLastError(2)}value=envObject.ensureHandleId(v[emnapiCtx.handleStore.get(key).value]);(growMemViews(),HEAPU32)[result>>2]=value;return envObject.getReturnStatus()}catch(err){envObject.tryCatch.setError(err);return envObject.setLastError(10)}}function _napi_get_all_property_names(env,object,key_mode,key_filter,key_conversion,result){var value;if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!envObject.tryCatch.isEmpty())return envObject.setLastError(10);if(!envObject.canCallIntoJs())return envObject.setLastError(envObject.moduleApiVersion>=10?23:10);envObject.clearLastError();try{if(!result)return envObject.setLastError(1);if(!object)return envObject.setLastError(1);var h=emnapiCtx.handleStore.get(object);if(h.value==null){throw new TypeError("Cannot convert undefined or null to object")}var obj=void 0;try{obj=h.isObject()||h.isFunction()?h.value:Object(h.value)}catch(_){return envObject.setLastError(2)}if(key_mode!==0&&key_mode!==1){return envObject.setLastError(1)}if(key_conversion!==0&&key_conversion!==1){return envObject.setLastError(1)}var props=[];var names=void 0;var symbols=void 0;var i=void 0;var own=true;var integerIndiceRegex=/^(0|[1-9][0-9]*)$/;do{names=Object.getOwnPropertyNames(obj);symbols=Object.getOwnPropertySymbols(obj);for(i=0;i>2]=value;return envObject.getReturnStatus()}catch(err){envObject.tryCatch.setError(err);return envObject.setLastError(10)}}function _napi_get_property_names(env,object,result){return _napi_get_all_property_names(env,object,0,2|16,1,result)}function _napi_get_reference_value(env,ref,result){if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!ref)return envObject.setLastError(1);if(!result)return envObject.setLastError(1);var reference=emnapiCtx.refStore.get(ref);var handleId=reference.get(envObject);(growMemViews(),HEAPU32)[result>>2]=handleId;return envObject.clearLastError()}function _napi_get_typedarray_info(env,typedarray,type,length,data,arraybuffer,byte_offset){if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!typedarray)return envObject.setLastError(1);var handle=emnapiCtx.handleStore.get(typedarray);if(!handle.isTypedArray()){return envObject.setLastError(1)}var v=handle.value;if(type){var t=void 0;if(v instanceof Int8Array){t=0}else if(v instanceof Uint8Array){t=1}else if(v instanceof Uint8ClampedArray){t=2}else if(v instanceof Int16Array){t=3}else if(v instanceof Uint16Array){t=4}else if(v instanceof Int32Array){t=5}else if(v instanceof Uint32Array){t=6}else if(typeof Float16Array==="function"&&v instanceof Float16Array){t=11}else if(v instanceof Float32Array){t=7}else if(v instanceof Float64Array){t=8}else if(v instanceof BigInt64Array){t=9}else if(v instanceof BigUint64Array){t=10}else{return envObject.setLastError(9)}(growMemViews(),HEAP32)[type>>2]=t}v=emnapiExternalMemory.getOrUpdateMemoryView(v);if(length){(growMemViews(),HEAPU32)[length>>2]=v.length}if(data||arraybuffer){if(data){var p=emnapiExternalMemory.getViewPointer(v,true).address;(growMemViews(),HEAPU32)[data>>2]=p}if(arraybuffer){var ab=envObject.ensureHandleId(v.buffer);(growMemViews(),HEAPU32)[arraybuffer>>2]=ab}}if(byte_offset){(growMemViews(),HEAPU32)[byte_offset>>2]=v.byteOffset}return envObject.clearLastError()}function _napi_get_undefined(env,result){if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!result)return envObject.setLastError(1);var value=1;(growMemViews(),HEAPU32)[result>>2]=value;return envObject.clearLastError()}function _napi_get_value_bool(env,value,result){if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!value)return envObject.setLastError(1);if(!result)return envObject.setLastError(1);var handle=emnapiCtx.handleStore.get(value);if(typeof handle.value!=="boolean"){return envObject.setLastError(7)}var r=handle.value?1:0;(growMemViews(),HEAP8)[result]=r;return envObject.clearLastError()}function _napi_get_value_double(env,value,result){if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!value)return envObject.setLastError(1);if(!result)return envObject.setLastError(1);var handle=emnapiCtx.handleStore.get(value);if(typeof handle.value!=="number"){return envObject.setLastError(6)}var r=handle.value;(growMemViews(),HEAPF64)[result>>3]=r;return envObject.clearLastError()}function _napi_get_value_int32(env,value,result){if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!value)return envObject.setLastError(1);if(!result)return envObject.setLastError(1);var handle=emnapiCtx.handleStore.get(value);if(typeof handle.value!=="number"){return envObject.setLastError(6)}var v=new Int32Array([handle.value])[0];(growMemViews(),HEAP32)[result>>2]=v;return envObject.clearLastError()}function emnapiSetValueI64(result,numberValue){var tempDouble;var tempI64=[numberValue>>>0,(tempDouble=numberValue,+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)];(growMemViews(),HEAP32)[result>>2]=tempI64[0];(growMemViews(),HEAP32)[result+4>>2]=tempI64[1]}function _napi_get_value_int64(env,value,result){if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!value)return envObject.setLastError(1);if(!result)return envObject.setLastError(1);var handle=emnapiCtx.handleStore.get(value);if(typeof handle.value!=="number"){return envObject.setLastError(6)}var numberValue=handle.value;if(numberValue===Number.POSITIVE_INFINITY||numberValue===Number.NEGATIVE_INFINITY||isNaN(numberValue)){(growMemViews(),HEAP32)[result>>2]=0;(growMemViews(),HEAP32)[result+4>>2]=0}else if(numberValue<-0x8000000000000000){(growMemViews(),HEAP32)[result>>2]=0;(growMemViews(),HEAP32)[result+4>>2]=2147483648}else if(numberValue>=0x8000000000000000){(growMemViews(),HEAPU32)[result>>2]=4294967295;(growMemViews(),HEAPU32)[result+4>>2]=2147483647}else{emnapiSetValueI64(result,Math.trunc(numberValue))}return envObject.clearLastError()}function _napi_get_value_string_utf8(env,value,buf,buf_size,result){if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!value)return envObject.setLastError(1);buf_size=buf_size>>>0;var handle=emnapiCtx.handleStore.get(value);if(typeof handle.value!=="string"){return envObject.setLastError(3)}if(!buf){if(!result)return envObject.setLastError(1);var strLength=emnapiString.lengthBytesUTF8(handle.value);(growMemViews(),HEAPU32)[result>>2]=strLength}else if(buf_size!==0){var copied=emnapiString.stringToUTF8(handle.value,buf,buf_size);if(result){(growMemViews(),HEAPU32)[result>>2]=copied}}else if(result){(growMemViews(),HEAPU32)[result>>2]=0}return envObject.clearLastError()}function _napi_get_value_uint32(env,value,result){if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!value)return envObject.setLastError(1);if(!result)return envObject.setLastError(1);var handle=emnapiCtx.handleStore.get(value);if(typeof handle.value!=="number"){return envObject.setLastError(6)}var v=new Uint32Array([handle.value])[0];(growMemViews(),HEAPU32)[result>>2]=v;return envObject.clearLastError()}function _napi_has_named_property(env,object,utf8name,result){var r;if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!envObject.tryCatch.isEmpty())return envObject.setLastError(10);if(!envObject.canCallIntoJs())return envObject.setLastError(envObject.moduleApiVersion>=10?23:10);envObject.clearLastError();try{if(!result)return envObject.setLastError(1);if(!object)return envObject.setLastError(1);if(!utf8name){return envObject.setLastError(1)}var h=emnapiCtx.handleStore.get(object);if(h.value==null){throw new TypeError("Cannot convert undefined or null to object")}var v=void 0;try{v=h.isObject()||h.isFunction()?h.value:Object(h.value)}catch(_){return envObject.setLastError(2)}r=emnapiString.UTF8ToString(utf8name,-1)in v;(growMemViews(),HEAP8)[result]=r?1:0;return envObject.getReturnStatus()}catch(err){envObject.tryCatch.setError(err);return envObject.setLastError(10)}}function _napi_has_own_property(env,object,key,result){var r;if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!envObject.tryCatch.isEmpty())return envObject.setLastError(10);if(!envObject.canCallIntoJs())return envObject.setLastError(envObject.moduleApiVersion>=10?23:10);envObject.clearLastError();try{if(!key)return envObject.setLastError(1);if(!result)return envObject.setLastError(1);if(!object)return envObject.setLastError(1);var h=emnapiCtx.handleStore.get(object);if(h.value==null){throw new TypeError("Cannot convert undefined or null to object")}var v=void 0;try{v=h.isObject()||h.isFunction()?h.value:Object(h.value)}catch(_){return envObject.setLastError(2)}var prop=emnapiCtx.handleStore.get(key).value;if(typeof prop!=="string"&&typeof prop!=="symbol"){return envObject.setLastError(4)}r=Object.prototype.hasOwnProperty.call(v,emnapiCtx.handleStore.get(key).value);(growMemViews(),HEAP8)[result]=r?1:0;return envObject.getReturnStatus()}catch(err){envObject.tryCatch.setError(err);return envObject.setLastError(10)}}function _napi_has_property(env,object,key,result){var r;if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!envObject.tryCatch.isEmpty())return envObject.setLastError(10);if(!envObject.canCallIntoJs())return envObject.setLastError(envObject.moduleApiVersion>=10?23:10);envObject.clearLastError();try{if(!key)return envObject.setLastError(1);if(!result)return envObject.setLastError(1);if(!object)return envObject.setLastError(1);var h=emnapiCtx.handleStore.get(object);if(h.value==null){throw new TypeError("Cannot convert undefined or null to object")}var v=void 0;try{v=h.isObject()||h.isFunction()?h.value:Object(h.value)}catch(_){return envObject.setLastError(2)}r=emnapiCtx.handleStore.get(key).value in v?1:0;(growMemViews(),HEAP8)[result]=r;return envObject.getReturnStatus()}catch(err){envObject.tryCatch.setError(err);return envObject.setLastError(10)}}function _napi_is_exception_pending(env,result){if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!result)return envObject.setLastError(1);var r=envObject.tryCatch.hasCaught();(growMemViews(),HEAP8)[result]=r?1:0;return envObject.clearLastError()}function _napi_open_escapable_handle_scope(env,result){if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!result)return envObject.setLastError(1);var scope=emnapiCtx.openScope(envObject);(growMemViews(),HEAPU32)[result>>2]=scope.id;return envObject.clearLastError()}function _napi_open_handle_scope(env,result){if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!result)return envObject.setLastError(1);var scope=emnapiCtx.openScope(envObject);(growMemViews(),HEAPU32)[result>>2]=scope.id;return envObject.clearLastError()}function _napi_set_element(env,object,index,value){if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!envObject.tryCatch.isEmpty())return envObject.setLastError(10);if(!envObject.canCallIntoJs())return envObject.setLastError(envObject.moduleApiVersion>=10?23:10);envObject.clearLastError();try{if(!value)return envObject.setLastError(1);if(!object)return envObject.setLastError(1);var h=emnapiCtx.handleStore.get(object);if(!(h.isObject()||h.isFunction())){return envObject.setLastError(2)}h.value[index>>>0]=emnapiCtx.handleStore.get(value).value;return envObject.getReturnStatus()}catch(err){envObject.tryCatch.setError(err);return envObject.setLastError(10)}}function _napi_set_last_error(env,error_code,engine_error_code,engine_reserved){var envObject=emnapiCtx.envStore.get(env);return envObject.setLastError(error_code,engine_error_code,engine_reserved)}function _napi_set_named_property(env,object,cname,value){if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!envObject.tryCatch.isEmpty())return envObject.setLastError(10);if(!envObject.canCallIntoJs())return envObject.setLastError(envObject.moduleApiVersion>=10?23:10);envObject.clearLastError();try{if(!value)return envObject.setLastError(1);if(!object)return envObject.setLastError(1);var h=emnapiCtx.handleStore.get(object);if(!(h.isObject()||h.isFunction())){return envObject.setLastError(2)}if(!cname){return envObject.setLastError(1)}emnapiCtx.handleStore.get(object).value[emnapiString.UTF8ToString(cname,-1)]=emnapiCtx.handleStore.get(value).value;return envObject.getReturnStatus()}catch(err){envObject.tryCatch.setError(err);return envObject.setLastError(10)}}function _napi_throw(env,error){if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!envObject.tryCatch.isEmpty())return envObject.setLastError(10);if(!envObject.canCallIntoJs())return envObject.setLastError(envObject.moduleApiVersion>=10?23:10);envObject.clearLastError();try{if(!error)return envObject.setLastError(1);envObject.tryCatch.setError(emnapiCtx.handleStore.get(error).value);return envObject.clearLastError()}catch(err){envObject.tryCatch.setError(err);return envObject.setLastError(10)}}function _napi_typeof(env,value,result){if(!env)return 1;var envObject=emnapiCtx.envStore.get(env);envObject.checkGCAccess();if(!value)return envObject.setLastError(1);if(!result)return envObject.setLastError(1);var v=emnapiCtx.handleStore.get(value);var r;if(v.isNumber()){r=3}else if(v.isBigInt()){r=9}else if(v.isString()){r=4}else if(v.isFunction()){r=7}else if(v.isExternal()){r=8}else if(v.isObject()){r=6}else if(v.isBoolean()){r=2}else if(v.isUndefined()){r=0}else if(v.isSymbol()){r=5}else if(v.isNull()){r=1}else{return envObject.setLastError(1)}(growMemViews(),HEAP32)[result>>2]=r;return envObject.clearLastError()}var _random_get=(buffer,size)=>randomFill((growMemViews(),HEAPU8).subarray(buffer,buffer+size));var emnapiModule={exports:{},loaded:false,filename:""};var emnapiAsyncWorkPoolSize=0;function emnapiInit(options){if(emnapiModule.loaded)return emnapiModule.exports;if(typeof options!=="object"||options===null){throw new TypeError("Invalid emnapi init option")}var context=options.context;if(typeof context!=="object"||context===null){throw new TypeError("Invalid `options.context`. Use `import { getDefaultContext } from '@emnapi/runtime'`")}emnapiCtx=context;var filename=typeof options.filename==="string"?options.filename:"";emnapiModule.filename=filename;if("nodeBinding"in options){var nodeBinding=options.nodeBinding;if(typeof nodeBinding!=="object"||nodeBinding===null){throw new TypeError("Invalid `options.nodeBinding`. Use @emnapi/node-binding package")}emnapiNodeBinding=nodeBinding}if("asyncWorkPoolSize"in options){if(typeof options.asyncWorkPoolSize!=="number"){throw new TypeError("options.asyncWorkPoolSize must be a integer")}emnapiAsyncWorkPoolSize=options.asyncWorkPoolSize>>0;if(emnapiAsyncWorkPoolSize>1024){emnapiAsyncWorkPoolSize=1024}else if(emnapiAsyncWorkPoolSize<-1024){emnapiAsyncWorkPoolSize=-1024}}var moduleApiVersion=_node_api_module_get_api_version_v1();var envObject=emnapiModule.envObject||(emnapiModule.envObject=emnapiCtx.createEnv(filename,moduleApiVersion,function(cb){return getWasmTableEntry(cb)},function(cb){return getWasmTableEntry(cb)},abort,emnapiNodeBinding));var scope=emnapiCtx.openScope(envObject);try{envObject.callIntoModule(function(_envObject){var exports=emnapiModule.exports;var exportsHandle=scope.add(exports);var napiValue=_napi_register_wasm_v1(_envObject.id,exportsHandle.id);emnapiModule.exports=!napiValue?exports:emnapiCtx.handleStore.get(napiValue).value})}catch(err){if(err!=="unwind"){throw err}}finally{emnapiCtx.closeScope(envObject,scope)}emnapiModule.loaded=true;delete emnapiModule.envObject;return emnapiModule.exports}PThread.init();FS.createPreloadedFile=FS_createPreloadedFile;FS.preloadFile=FS_preloadFile;FS.staticInit();if(ENVIRONMENT_IS_NODE){NODEFS.staticInit()}if(!ENVIRONMENT_IS_NODE){throw new Error("NODERAWFS is currently only supported on Node.js environment.")}var nodeTTY=require("node:tty");function _wrapNodeError(func){return(...args)=>{try{return func(...args)}catch(e){if(e.name=="BadResource"){e.code="EBADF"}if(e.code){throw new FS.ErrnoError(ERRNO_CODES[e.code])}throw e}}}function _wrapNodeStreamFunc(func,vfs_func){return _wrapNodeError((stream,...args)=>{if(stream.stream_ops){return vfs_func(stream,...args)}return func(stream,...args)})}var VFS={...FS};for(const[key,value]of Object.entries(NODERAWFS)){FS[key]=_wrapNodeError(value)}for(const[key,value]of Object.entries(NODERAWFS_stream_funcs)){FS[key]=_wrapNodeStreamFunc(value,FS[key])}emnapiExternalMemory.init();emnapiString.init();{initMemory();if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["preloadPlugins"])preloadPlugins=Module["preloadPlugins"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];if(Module["arguments"])programArgs=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].shift()()}}}Module["emnapiInit"]=emnapiInit;var proxiedFunctionTable=[_proc_exit,exitOnMainThread,pthreadCreateProxied,___syscall_dup,___syscall_faccessat,___syscall_fcntl64,___syscall_fstat64,___syscall_ftruncate64,___syscall_getcwd,___syscall_ioctl,___syscall_lstat64,___syscall_newfstatat,___syscall_openat,___syscall_poll,___syscall_poll_nonblocking,___syscall_rmdir,___syscall_stat64,___syscall_unlinkat,__mmap_js,__munmap_js,_environ_get,_environ_sizes_get,_fd_close,_fd_fdstat_get,_fd_read,_fd_seek,_fd_write];function unbox_small_structs(type_ptr){type_ptr=type_ptr;var type_id=(growMemViews(),HEAPU16)[(type_ptr+6>>1)+0];while(type_id===13){if((growMemViews(),HEAPU32)[(type_ptr>>2)+0]>16){break}var elements=(growMemViews(),HEAPU32)[(type_ptr+8>>2)+0];var first_element=(growMemViews(),HEAPU32)[(elements>>2)+0];if(first_element===0){type_id=0;break}else if((growMemViews(),HEAPU32)[(elements>>2)+1]===0){type_ptr=first_element;type_id=(growMemViews(),HEAPU16)[(first_element+6>>1)+0]}else{break}}return[type_ptr,type_id]}function ffi_call_js(cif,fn,rvalue,avalue){cif=cif;fn=fn;rvalue=rvalue;avalue=avalue;var abi=(growMemViews(),HEAPU32)[(cif>>2)+0];var nargs=(growMemViews(),HEAPU32)[(cif>>2)+1];var nfixedargs=(growMemViews(),HEAPU32)[(cif>>2)+6];var arg_types_ptr=(growMemViews(),HEAPU32)[(cif>>2)+2];var flags=(growMemViews(),HEAPU32)[(cif>>2)+5];var rtype_unboxed=unbox_small_structs((growMemViews(),HEAPU32)[(cif>>2)+3]);var rtype_ptr=rtype_unboxed[0];var rtype_id=rtype_unboxed[1];var orig_stack_ptr=stackSave();var cur_stack_ptr=orig_stack_ptr;var args=[];var ret_by_arg=!!0;if(rtype_id===15){throw new Error("complex ret marshalling nyi")}if(rtype_id<0||rtype_id>17){throw new Error("Unexpected rtype "+rtype_id)}if(rtype_id===4||rtype_id===13){args.push(rvalue);ret_by_arg=!!1}for(var i=0;i>2)+i];var arg_unboxed=unbox_small_structs((growMemViews(),HEAPU32)[(arg_types_ptr>>2)+i]);var arg_type_ptr=arg_unboxed[0];var arg_type_id=arg_unboxed[1];switch(arg_type_id){case 1:case 10:case 9:args.push((growMemViews(),HEAPU32)[(arg_ptr>>2)+0]);break;case 2:args.push((growMemViews(),HEAPF32)[(arg_ptr>>2)+0]);break;case 3:args.push((growMemViews(),HEAPF64)[(arg_ptr>>3)+0]);break;case 5:args.push((growMemViews(),HEAPU8)[arg_ptr+0]);break;case 6:args.push((growMemViews(),HEAP8)[arg_ptr+0]);break;case 7:args.push((growMemViews(),HEAPU16)[(arg_ptr>>1)+0]);break;case 8:args.push((growMemViews(),HEAP16)[(arg_ptr>>1)+0]);break;case 11:case 12:args.push((growMemViews(),HEAPU64)[(arg_ptr>>3)+0]);break;case 4:args.push((growMemViews(),HEAPU64)[(arg_ptr>>3)+0]);args.push((growMemViews(),HEAPU64)[(arg_ptr>>3)+1]);break;case 13:var size=(growMemViews(),HEAPU32)[(arg_type_ptr>>2)+0];var align=(growMemViews(),HEAPU16)[(arg_type_ptr+4>>1)+0];cur_stack_ptr-=size,cur_stack_ptr&=~(align-1);(growMemViews(),HEAP8).subarray(cur_stack_ptr,cur_stack_ptr+size).set((growMemViews(),HEAP8).subarray(arg_ptr,arg_ptr+size));args.push(cur_stack_ptr);break;case 14:args.push((growMemViews(),HEAPU32)[(arg_ptr>>2)+0]);break;case 15:throw new Error("complex marshalling nyi");default:throw new Error("Unexpected type "+arg_type_id)}}if(flags&1){var struct_arg_info=[];for(var i=nargs-1;i>=nfixedargs;i--){var arg_ptr=(growMemViews(),HEAPU32)[(avalue>>2)+i];var arg_unboxed=unbox_small_structs((growMemViews(),HEAPU32)[(arg_types_ptr>>2)+i]);var arg_type_ptr=arg_unboxed[0];var arg_type_id=arg_unboxed[1];switch(arg_type_id){case 5:case 6:cur_stack_ptr-=1,cur_stack_ptr&=~(1-1);(growMemViews(),HEAPU8)[cur_stack_ptr+0]=(growMemViews(),HEAPU8)[arg_ptr+0];break;case 7:case 8:cur_stack_ptr-=2,cur_stack_ptr&=~(2-1);(growMemViews(),HEAPU16)[(cur_stack_ptr>>1)+0]=(growMemViews(),HEAPU16)[(arg_ptr>>1)+0];break;case 1:case 9:case 10:case 2:cur_stack_ptr-=4,cur_stack_ptr&=~(4-1);(growMemViews(),HEAPU32)[(cur_stack_ptr>>2)+0]=(growMemViews(),HEAPU32)[(arg_ptr>>2)+0];break;case 3:case 11:case 12:cur_stack_ptr-=8,cur_stack_ptr&=~(8-1);(growMemViews(),HEAPU32)[(cur_stack_ptr>>2)+0]=(growMemViews(),HEAPU32)[(arg_ptr>>2)+0];(growMemViews(),HEAPU32)[(cur_stack_ptr>>2)+1]=(growMemViews(),HEAPU32)[(arg_ptr>>2)+1];break;case 4:cur_stack_ptr-=16,cur_stack_ptr&=~(8-1);(growMemViews(),HEAPU32)[(cur_stack_ptr>>2)+0]=(growMemViews(),HEAPU32)[(arg_ptr>>2)+0];(growMemViews(),HEAPU32)[(cur_stack_ptr>>2)+1]=(growMemViews(),HEAPU32)[(arg_ptr>>2)+1];(growMemViews(),HEAPU32)[(cur_stack_ptr>>2)+2]=(growMemViews(),HEAPU32)[(arg_ptr>>2)+2];(growMemViews(),HEAPU32)[(cur_stack_ptr>>2)+3]=(growMemViews(),HEAPU32)[(arg_ptr>>2)+3];break;case 13:cur_stack_ptr-=4,cur_stack_ptr&=~(4-1);struct_arg_info.push([cur_stack_ptr,arg_ptr,(growMemViews(),HEAPU32)[(arg_type_ptr>>2)+0],(growMemViews(),HEAPU16)[(arg_type_ptr+4>>1)+0]]);break;case 14:cur_stack_ptr-=4,cur_stack_ptr&=~(4-1);(growMemViews(),HEAPU32)[(cur_stack_ptr>>2)+0]=(growMemViews(),HEAPU32)[(arg_ptr>>2)+0];break;case 15:throw new Error("complex arg marshalling nyi");default:throw new Error("Unexpected argtype "+arg_type_id)}}args.push(cur_stack_ptr);for(var i=0;i>2)+0]=cur_stack_ptr}}stackRestore(cur_stack_ptr);stackAlloc(0);var result=getWasmTableEntry(fn).apply(null,args);stackRestore(orig_stack_ptr);if(ret_by_arg){return}switch(rtype_id){case 0:break;case 1:case 9:case 10:(growMemViews(),HEAPU32)[(rvalue>>2)+0]=result;break;case 2:(growMemViews(),HEAPF32)[(rvalue>>2)+0]=result;break;case 3:(growMemViews(),HEAPF64)[(rvalue>>3)+0]=result;break;case 5:case 6:(growMemViews(),HEAPU8)[rvalue+0]=result;break;case 7:case 8:(growMemViews(),HEAPU16)[(rvalue>>1)+0]=result;break;case 11:case 12:(growMemViews(),HEAPU64)[(rvalue>>3)+0]=result;break;case 14:(growMemViews(),HEAPU32)[(rvalue>>2)+0]=result;break;case 15:throw new Error("complex ret marshalling nyi");default:throw new Error("Unexpected rtype "+rtype_id)}}var _free,_malloc,_uv_library_shutdown,_pthread_self,_node_api_module_get_api_version_v1,_napi_register_wasm_v1,_vips_shutdown,__emscripten_tls_init,_emscripten_builtin_memalign,__emscripten_thread_init,___set_thread_state,__emscripten_thread_crashed,__emscripten_run_js_on_main_thread_done,__emscripten_run_js_on_main_thread,__emscripten_thread_free_data,__emscripten_thread_exit,__emscripten_check_mailbox,___trap,_emscripten_stack_set_limits,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,__indirect_function_table,wasmTable;function assignWasmExports(wasmExports){_free=Module["_free"]=wasmExports["jb"];_malloc=Module["_malloc"]=wasmExports["kb"];_uv_library_shutdown=Module["_uv_library_shutdown"]=wasmExports["mb"];_pthread_self=wasmExports["nb"];_node_api_module_get_api_version_v1=Module["_node_api_module_get_api_version_v1"]=wasmExports["ob"];_napi_register_wasm_v1=Module["_napi_register_wasm_v1"]=wasmExports["pb"];_vips_shutdown=Module["_vips_shutdown"]=wasmExports["qb"];__emscripten_tls_init=wasmExports["rb"];_emscripten_builtin_memalign=wasmExports["sb"];__emscripten_thread_init=wasmExports["tb"];___set_thread_state=wasmExports["ub"];__emscripten_thread_crashed=wasmExports["vb"];__emscripten_run_js_on_main_thread_done=wasmExports["wb"];__emscripten_run_js_on_main_thread=wasmExports["xb"];__emscripten_thread_free_data=wasmExports["yb"];__emscripten_thread_exit=wasmExports["zb"];__emscripten_check_mailbox=wasmExports["Ab"];___trap=wasmExports["Bb"];_emscripten_stack_set_limits=wasmExports["Cb"];__emscripten_stack_restore=wasmExports["Db"];__emscripten_stack_alloc=wasmExports["Eb"];_emscripten_stack_get_current=wasmExports["Fb"];__indirect_function_table=wasmTable=wasmExports["lb"]}var wasmImports;function assignWasmImports(){wasmImports={c:___assert_fail,$a:___call_sighandler,bb:___pthread_create_js,ra:___syscall_dup,ua:___syscall_faccessat,R:___syscall_fcntl64,oa:___syscall_fstat64,ka:___syscall_ftruncate64,ja:___syscall_getcwd,ya:___syscall_ioctl,la:___syscall_lstat64,ma:___syscall_newfstatat,D:___syscall_openat,cb:___syscall_poll,db:___syscall_poll_nonblocking,_a:___syscall_rmdir,na:___syscall_stat64,_:___syscall_unlinkat,va:__abort_js,Z:__emnapi_callback_into_module,ta:__emnapi_ctx_decrease_waiting_request_counter,Ea:__emnapi_ctx_increase_waiting_request_counter,O:__emnapi_env_check_gc_access,hb:__emnapi_get_last_error_info,Ua:__emnapi_node_emit_async_destroy,Va:__emnapi_node_emit_async_init,Sa:__emnapi_node_make_callback,Qa:__emnapi_set_immediate,Ra:__emnapi_worker_unref,ga:__emscripten_init_main_thread_js,Ya:__emscripten_notify_mailbox_postmessage,ba:__emscripten_receive_on_main_thread_js,ab:__emscripten_runtime_keepalive_clear,$:__emscripten_thread_cleanup,fa:__emscripten_thread_mailbox_await,qa:__emscripten_thread_set_strongref,ca:__gmtime_js,da:__localtime_js,eb:__mmap_js,fb:__munmap_js,xa:__tzset_js,sa:_clock_time_get,Ta:_emnapi_is_node_binding_available,aa:_emscripten_check_blocking_allowed,P:_emscripten_date_now,pa:_emscripten_exit_with_live_runtime,Za:_emscripten_get_heap_max,x:_emscripten_get_now,E:_emscripten_num_logical_cores,Xa:_emscripten_resize_heap,Aa:_emscripten_runtime_keepalive_pop,Ka:_emscripten_runtime_keepalive_push,za:_environ_get,Ba:_environ_sizes_get,F:_exit,u:_fd_close,ha:_fd_fdstat_get,Q:_fd_read,ea:_fd_seek,y:_fd_write,S:ffi_call_js,a:wasmMemory,T:_napi_add_finalizer,L:_napi_call_function,C:_napi_clear_last_error,z:_napi_close_escapable_handle_scope,m:_napi_close_handle_scope,gb:_napi_coerce_to_object,Wa:_napi_coerce_to_string,U:_napi_create_array,G:_napi_create_array_with_length,V:_napi_create_buffer_copy,n:_napi_create_double,J:_napi_create_error,Fa:_napi_create_external_buffer,N:_napi_create_function,d:_napi_create_object,l:_napi_create_reference,Ja:_napi_create_string_latin1,i:_napi_create_string_utf8,Na:_napi_create_type_error,La:_napi_define_properties,h:_napi_delete_reference,H:_napi_escape_handle,Ma:_napi_fatal_error,Oa:_napi_get_and_clear_last_exception,j:_napi_get_array_length,k:_napi_get_boolean,M:_napi_get_cb_info,o:_napi_get_element,e:_napi_get_named_property,v:_napi_get_null,Ga:_napi_get_property,Da:_napi_get_property_names,g:_napi_get_reference_value,W:_napi_get_typedarray_info,f:_napi_get_undefined,A:_napi_get_value_bool,Y:_napi_get_value_double,K:_napi_get_value_int32,Pa:_napi_get_value_int64,X:_napi_get_value_string_utf8,B:_napi_get_value_uint32,s:_napi_has_named_property,Ca:_napi_has_own_property,Ha:_napi_has_property,r:_napi_is_exception_pending,I:_napi_open_escapable_handle_scope,p:_napi_open_handle_scope,w:_napi_set_element,q:_napi_set_last_error,b:_napi_set_named_property,Ia:_napi_throw,t:_napi_typeof,wa:_proc_exit,ia:_random_get}}async function run(){if(ENVIRONMENT_IS_PTHREAD){initRuntime();return}preRun();if(runDependencies>0){await new Promise(resolve=>dependenciesFulfilled=resolve)}var setStatus=Module["setStatus"];if(setStatus){setStatus("Running...");await new Promise(resolve=>setTimeout(resolve,1));setTimeout(setStatus,1,"")}if(ABORT)return;initRuntime();Module["onRuntimeInitialized"]?.();postRun()}var wasmExports;if(!ENVIRONMENT_IS_PTHREAD){wasmExports=createWasm();run()} diff --git a/node_modules/@img/sharp-wasm32/lib/sharp-wasm32-0.35.3.node.wasm b/node_modules/@img/sharp-wasm32/lib/sharp-wasm32-0.35.3.node.wasm new file mode 100644 index 0000000..789d807 Binary files /dev/null and b/node_modules/@img/sharp-wasm32/lib/sharp-wasm32-0.35.3.node.wasm differ diff --git a/node_modules/@img/sharp-wasm32/package.json b/node_modules/@img/sharp-wasm32/package.json new file mode 100644 index 0000000..7e94a76 --- /dev/null +++ b/node_modules/@img/sharp-wasm32/package.json @@ -0,0 +1,37 @@ +{ + "name": "@img/sharp-wasm32", + "version": "0.35.3", + "description": "Prebuilt sharp for use with WebAssembly", + "author": "Lovell Fuller ", + "homepage": "https://sharp.pixelplumbing.com", + "repository": { + "type": "git", + "url": "git+https://github.com/lovell/sharp.git", + "directory": "npm/wasm32" + }, + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "funding": { + "url": "https://opencollective.com/libvips" + }, + "preferUnplugged": true, + "files": [ + "index.cjs", + "lib", + "versions.json" + ], + "publishConfig": { + "access": "public" + }, + "type": "commonjs", + "exports": { + "./sharp.node": "./index.cjs", + "./package": "./package.json", + "./versions": "./versions.json" + }, + "engines": { + "node": ">=20.9.0" + }, + "dependencies": { + "@emnapi/runtime": "^1.11.1" + } +} diff --git a/node_modules/@img/sharp-wasm32/versions.json b/node_modules/@img/sharp-wasm32/versions.json new file mode 100644 index 0000000..5f8dae1 --- /dev/null +++ b/node_modules/@img/sharp-wasm32/versions.json @@ -0,0 +1,21 @@ +{ + "aom": "3.14.1", + "cgif": "0.5.3", + "emscripten": "6.0.1", + "exif": "0.6.26", + "expat": "2.8.2", + "ffi": "3.6.0", + "glib": "2.89.1", + "heif": "1.23.1", + "highway": "1.4.0", + "imagequant": "2.4.1", + "lcms": "2.19.1", + "mozjpeg": "0826579", + "png": "1.6.58", + "resvg": "0.47.0", + "tiff": "4.7.2rc2", + "uhdr": "1acdbed", + "vips": "8.18.3", + "webp": "1.6.0", + "zlib-ng": "2.3.3" +} \ No newline at end of file diff --git a/node_modules/accepts/HISTORY.md b/node_modules/accepts/HISTORY.md new file mode 100644 index 0000000..627a81d --- /dev/null +++ b/node_modules/accepts/HISTORY.md @@ -0,0 +1,250 @@ +2.0.0 / 2024-08-31 +================== + + * Drop node <18 support + * deps: mime-types@^3.0.0 + * deps: negotiator@^1.0.0 + +1.3.8 / 2022-02-02 +================== + + * deps: mime-types@~2.1.34 + - deps: mime-db@~1.51.0 + * deps: negotiator@0.6.3 + +1.3.7 / 2019-04-29 +================== + + * deps: negotiator@0.6.2 + - Fix sorting charset, encoding, and language with extra parameters + +1.3.6 / 2019-04-28 +================== + + * deps: mime-types@~2.1.24 + - deps: mime-db@~1.40.0 + +1.3.5 / 2018-02-28 +================== + + * deps: mime-types@~2.1.18 + - deps: mime-db@~1.33.0 + +1.3.4 / 2017-08-22 +================== + + * deps: mime-types@~2.1.16 + - deps: mime-db@~1.29.0 + +1.3.3 / 2016-05-02 +================== + + * deps: mime-types@~2.1.11 + - deps: mime-db@~1.23.0 + * deps: negotiator@0.6.1 + - perf: improve `Accept` parsing speed + - perf: improve `Accept-Charset` parsing speed + - perf: improve `Accept-Encoding` parsing speed + - perf: improve `Accept-Language` parsing speed + +1.3.2 / 2016-03-08 +================== + + * deps: mime-types@~2.1.10 + - Fix extension of `application/dash+xml` + - Update primary extension for `audio/mp4` + - deps: mime-db@~1.22.0 + +1.3.1 / 2016-01-19 +================== + + * deps: mime-types@~2.1.9 + - deps: mime-db@~1.21.0 + +1.3.0 / 2015-09-29 +================== + + * deps: mime-types@~2.1.7 + - deps: mime-db@~1.19.0 + * deps: negotiator@0.6.0 + - Fix including type extensions in parameters in `Accept` parsing + - Fix parsing `Accept` parameters with quoted equals + - Fix parsing `Accept` parameters with quoted semicolons + - Lazy-load modules from main entry point + - perf: delay type concatenation until needed + - perf: enable strict mode + - perf: hoist regular expressions + - perf: remove closures getting spec properties + - perf: remove a closure from media type parsing + - perf: remove property delete from media type parsing + +1.2.13 / 2015-09-06 +=================== + + * deps: mime-types@~2.1.6 + - deps: mime-db@~1.18.0 + +1.2.12 / 2015-07-30 +=================== + + * deps: mime-types@~2.1.4 + - deps: mime-db@~1.16.0 + +1.2.11 / 2015-07-16 +=================== + + * deps: mime-types@~2.1.3 + - deps: mime-db@~1.15.0 + +1.2.10 / 2015-07-01 +=================== + + * deps: mime-types@~2.1.2 + - deps: mime-db@~1.14.0 + +1.2.9 / 2015-06-08 +================== + + * deps: mime-types@~2.1.1 + - perf: fix deopt during mapping + +1.2.8 / 2015-06-07 +================== + + * deps: mime-types@~2.1.0 + - deps: mime-db@~1.13.0 + * perf: avoid argument reassignment & argument slice + * perf: avoid negotiator recursive construction + * perf: enable strict mode + * perf: remove unnecessary bitwise operator + +1.2.7 / 2015-05-10 +================== + + * deps: negotiator@0.5.3 + - Fix media type parameter matching to be case-insensitive + +1.2.6 / 2015-05-07 +================== + + * deps: mime-types@~2.0.11 + - deps: mime-db@~1.9.1 + * deps: negotiator@0.5.2 + - Fix comparing media types with quoted values + - Fix splitting media types with quoted commas + +1.2.5 / 2015-03-13 +================== + + * deps: mime-types@~2.0.10 + - deps: mime-db@~1.8.0 + +1.2.4 / 2015-02-14 +================== + + * Support Node.js 0.6 + * deps: mime-types@~2.0.9 + - deps: mime-db@~1.7.0 + * deps: negotiator@0.5.1 + - Fix preference sorting to be stable for long acceptable lists + +1.2.3 / 2015-01-31 +================== + + * deps: mime-types@~2.0.8 + - deps: mime-db@~1.6.0 + +1.2.2 / 2014-12-30 +================== + + * deps: mime-types@~2.0.7 + - deps: mime-db@~1.5.0 + +1.2.1 / 2014-12-30 +================== + + * deps: mime-types@~2.0.5 + - deps: mime-db@~1.3.1 + +1.2.0 / 2014-12-19 +================== + + * deps: negotiator@0.5.0 + - Fix list return order when large accepted list + - Fix missing identity encoding when q=0 exists + - Remove dynamic building of Negotiator class + +1.1.4 / 2014-12-10 +================== + + * deps: mime-types@~2.0.4 + - deps: mime-db@~1.3.0 + +1.1.3 / 2014-11-09 +================== + + * deps: mime-types@~2.0.3 + - deps: mime-db@~1.2.0 + +1.1.2 / 2014-10-14 +================== + + * deps: negotiator@0.4.9 + - Fix error when media type has invalid parameter + +1.1.1 / 2014-09-28 +================== + + * deps: mime-types@~2.0.2 + - deps: mime-db@~1.1.0 + * deps: negotiator@0.4.8 + - Fix all negotiations to be case-insensitive + - Stable sort preferences of same quality according to client order + +1.1.0 / 2014-09-02 +================== + + * update `mime-types` + +1.0.7 / 2014-07-04 +================== + + * Fix wrong type returned from `type` when match after unknown extension + +1.0.6 / 2014-06-24 +================== + + * deps: negotiator@0.4.7 + +1.0.5 / 2014-06-20 +================== + + * fix crash when unknown extension given + +1.0.4 / 2014-06-19 +================== + + * use `mime-types` + +1.0.3 / 2014-06-11 +================== + + * deps: negotiator@0.4.6 + - Order by specificity when quality is the same + +1.0.2 / 2014-05-29 +================== + + * Fix interpretation when header not in request + * deps: pin negotiator@0.4.5 + +1.0.1 / 2014-01-18 +================== + + * Identity encoding isn't always acceptable + * deps: negotiator@~0.4.0 + +1.0.0 / 2013-12-27 +================== + + * Genesis diff --git a/node_modules/accepts/LICENSE b/node_modules/accepts/LICENSE new file mode 100644 index 0000000..0616607 --- /dev/null +++ b/node_modules/accepts/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2015 Douglas Christopher Wilson + +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. diff --git a/node_modules/accepts/README.md b/node_modules/accepts/README.md new file mode 100644 index 0000000..f3f10c4 --- /dev/null +++ b/node_modules/accepts/README.md @@ -0,0 +1,140 @@ +# accepts + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][github-actions-ci-image]][github-actions-ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Higher level content negotiation based on [negotiator](https://www.npmjs.com/package/negotiator). +Extracted from [koa](https://www.npmjs.com/package/koa) for general use. + +In addition to negotiator, it allows: + +- Allows types as an array or arguments list, ie `(['text/html', 'application/json'])` + as well as `('text/html', 'application/json')`. +- Allows type shorthands such as `json`. +- Returns `false` when no types match +- Treats non-existent headers as `*` + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install accepts +``` + +## API + +```js +var accepts = require('accepts') +``` + +### accepts(req) + +Create a new `Accepts` object for the given `req`. + +#### .charset(charsets) + +Return the first accepted charset. If nothing in `charsets` is accepted, +then `false` is returned. + +#### .charsets() + +Return the charsets that the request accepts, in the order of the client's +preference (most preferred first). + +#### .encoding(encodings) + +Return the first accepted encoding. If nothing in `encodings` is accepted, +then `false` is returned. + +#### .encodings() + +Return the encodings that the request accepts, in the order of the client's +preference (most preferred first). + +#### .language(languages) + +Return the first accepted language. If nothing in `languages` is accepted, +then `false` is returned. + +#### .languages() + +Return the languages that the request accepts, in the order of the client's +preference (most preferred first). + +#### .type(types) + +Return the first accepted type (and it is returned as the same text as what +appears in the `types` array). If nothing in `types` is accepted, then `false` +is returned. + +The `types` array can contain full MIME types or file extensions. Any value +that is not a full MIME type is passed to `require('mime-types').lookup`. + +#### .types() + +Return the types that the request accepts, in the order of the client's +preference (most preferred first). + +## Examples + +### Simple type negotiation + +This simple example shows how to use `accepts` to return a different typed +respond body based on what the client wants to accept. The server lists it's +preferences in order and will get back the best match between the client and +server. + +```js +var accepts = require('accepts') +var http = require('http') + +function app (req, res) { + var accept = accepts(req) + + // the order of this list is significant; should be server preferred order + switch (accept.type(['json', 'html'])) { + case 'json': + res.setHeader('Content-Type', 'application/json') + res.write('{"hello":"world!"}') + break + case 'html': + res.setHeader('Content-Type', 'text/html') + res.write('hello, world!') + break + default: + // the fallback is text/plain, so no need to specify it above + res.setHeader('Content-Type', 'text/plain') + res.write('hello, world!') + break + } + + res.end() +} + +http.createServer(app).listen(3000) +``` + +You can test this out with the cURL program: +```sh +curl -I -H'Accept: text/html' http://localhost:3000/ +``` + +## License + +[MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/accepts/master +[coveralls-url]: https://coveralls.io/r/jshttp/accepts?branch=master +[github-actions-ci-image]: https://badgen.net/github/checks/jshttp/accepts/master?label=ci +[github-actions-ci-url]: https://github.com/jshttp/accepts/actions/workflows/ci.yml +[node-version-image]: https://badgen.net/npm/node/accepts +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/accepts +[npm-url]: https://npmjs.org/package/accepts +[npm-version-image]: https://badgen.net/npm/v/accepts diff --git a/node_modules/accepts/index.js b/node_modules/accepts/index.js new file mode 100644 index 0000000..4f2840c --- /dev/null +++ b/node_modules/accepts/index.js @@ -0,0 +1,238 @@ +/*! + * accepts + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var Negotiator = require('negotiator') +var mime = require('mime-types') + +/** + * Module exports. + * @public + */ + +module.exports = Accepts + +/** + * Create a new Accepts object for the given req. + * + * @param {object} req + * @public + */ + +function Accepts (req) { + if (!(this instanceof Accepts)) { + return new Accepts(req) + } + + this.headers = req.headers + this.negotiator = new Negotiator(req) +} + +/** + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single mime type string + * such as "application/json", the extension name + * such as "json" or an array `["json", "html", "text/plain"]`. When a list + * or array is given the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * this.types('html'); + * // => "html" + * + * // Accept: text/*, application/json + * this.types('html'); + * // => "html" + * this.types('text/html'); + * // => "text/html" + * this.types('json', 'text'); + * // => "json" + * this.types('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * this.types('image/png'); + * this.types('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * this.types(['html', 'json']); + * this.types('html', 'json'); + * // => "json" + * + * @param {String|Array} types... + * @return {String|Array|Boolean} + * @public + */ + +Accepts.prototype.type = +Accepts.prototype.types = function (types_) { + var types = types_ + + // support flattened arguments + if (types && !Array.isArray(types)) { + types = new Array(arguments.length) + for (var i = 0; i < types.length; i++) { + types[i] = arguments[i] + } + } + + // no types, return all requested types + if (!types || types.length === 0) { + return this.negotiator.mediaTypes() + } + + // no accept header, return first given type + if (!this.headers.accept) { + return types[0] + } + + var mimes = types.map(extToMime) + var accepts = this.negotiator.mediaTypes(mimes.filter(validMime)) + var first = accepts[0] + + return first + ? types[mimes.indexOf(first)] + : false +} + +/** + * Return accepted encodings or best fit based on `encodings`. + * + * Given `Accept-Encoding: gzip, deflate` + * an array sorted by quality is returned: + * + * ['gzip', 'deflate'] + * + * @param {String|Array} encodings... + * @return {String|Array} + * @public + */ + +Accepts.prototype.encoding = +Accepts.prototype.encodings = function (encodings_) { + var encodings = encodings_ + + // support flattened arguments + if (encodings && !Array.isArray(encodings)) { + encodings = new Array(arguments.length) + for (var i = 0; i < encodings.length; i++) { + encodings[i] = arguments[i] + } + } + + // no encodings, return all requested encodings + if (!encodings || encodings.length === 0) { + return this.negotiator.encodings() + } + + return this.negotiator.encodings(encodings)[0] || false +} + +/** + * Return accepted charsets or best fit based on `charsets`. + * + * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5` + * an array sorted by quality is returned: + * + * ['utf-8', 'utf-7', 'iso-8859-1'] + * + * @param {String|Array} charsets... + * @return {String|Array} + * @public + */ + +Accepts.prototype.charset = +Accepts.prototype.charsets = function (charsets_) { + var charsets = charsets_ + + // support flattened arguments + if (charsets && !Array.isArray(charsets)) { + charsets = new Array(arguments.length) + for (var i = 0; i < charsets.length; i++) { + charsets[i] = arguments[i] + } + } + + // no charsets, return all requested charsets + if (!charsets || charsets.length === 0) { + return this.negotiator.charsets() + } + + return this.negotiator.charsets(charsets)[0] || false +} + +/** + * Return accepted languages or best fit based on `langs`. + * + * Given `Accept-Language: en;q=0.8, es, pt` + * an array sorted by quality is returned: + * + * ['es', 'pt', 'en'] + * + * @param {String|Array} langs... + * @return {Array|String} + * @public + */ + +Accepts.prototype.lang = +Accepts.prototype.langs = +Accepts.prototype.language = +Accepts.prototype.languages = function (languages_) { + var languages = languages_ + + // support flattened arguments + if (languages && !Array.isArray(languages)) { + languages = new Array(arguments.length) + for (var i = 0; i < languages.length; i++) { + languages[i] = arguments[i] + } + } + + // no languages, return all requested languages + if (!languages || languages.length === 0) { + return this.negotiator.languages() + } + + return this.negotiator.languages(languages)[0] || false +} + +/** + * Convert extnames to mime. + * + * @param {String} type + * @return {String} + * @private + */ + +function extToMime (type) { + return type.indexOf('/') === -1 + ? mime.lookup(type) + : type +} + +/** + * Check if mime is valid. + * + * @param {String} type + * @return {Boolean} + * @private + */ + +function validMime (type) { + return typeof type === 'string' +} diff --git a/node_modules/accepts/package.json b/node_modules/accepts/package.json new file mode 100644 index 0000000..b35b262 --- /dev/null +++ b/node_modules/accepts/package.json @@ -0,0 +1,47 @@ +{ + "name": "accepts", + "description": "Higher-level content negotiation", + "version": "2.0.0", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "repository": "jshttp/accepts", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "devDependencies": { + "deep-equal": "1.0.1", + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.25.4", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "4.3.1", + "eslint-plugin-standard": "4.1.0", + "mocha": "9.2.0", + "nyc": "15.1.0" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + }, + "keywords": [ + "content", + "negotiation", + "accept", + "accepts" + ] +} diff --git a/node_modules/append-field/.npmignore b/node_modules/append-field/.npmignore new file mode 100644 index 0000000..c2658d7 --- /dev/null +++ b/node_modules/append-field/.npmignore @@ -0,0 +1 @@ +node_modules/ diff --git a/node_modules/append-field/LICENSE b/node_modules/append-field/LICENSE new file mode 100644 index 0000000..14b1f89 --- /dev/null +++ b/node_modules/append-field/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Linus Unnebäck + +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. diff --git a/node_modules/append-field/README.md b/node_modules/append-field/README.md new file mode 100644 index 0000000..62b901b --- /dev/null +++ b/node_modules/append-field/README.md @@ -0,0 +1,44 @@ +# `append-field` + +A [W3C HTML JSON forms spec](http://www.w3.org/TR/html-json-forms/) compliant +field appender (for lack of a better name). Useful for people implementing +`application/x-www-form-urlencoded` and `multipart/form-data` parsers. + +It works best on objects created with `Object.create(null)`. Otherwise it might +conflict with variables from the prototype (e.g. `hasOwnProperty`). + +## Installation + +```sh +npm install --save append-field +``` + +## Usage + +```javascript +var appendField = require('append-field') +var obj = Object.create(null) + +appendField(obj, 'pets[0][species]', 'Dahut') +appendField(obj, 'pets[0][name]', 'Hypatia') +appendField(obj, 'pets[1][species]', 'Felis Stultus') +appendField(obj, 'pets[1][name]', 'Billie') + +console.log(obj) +``` + +```text +{ pets: + [ { species: 'Dahut', name: 'Hypatia' }, + { species: 'Felis Stultus', name: 'Billie' } ] } +``` + +## API + +### `appendField(store, key, value)` + +Adds the field named `key` with the value `value` to the object `store`. + +## License + +MIT diff --git a/node_modules/append-field/index.js b/node_modules/append-field/index.js new file mode 100644 index 0000000..fc5acc8 --- /dev/null +++ b/node_modules/append-field/index.js @@ -0,0 +1,12 @@ +var parsePath = require('./lib/parse-path') +var setValue = require('./lib/set-value') + +function appendField (store, key, value) { + var steps = parsePath(key) + + steps.reduce(function (context, step) { + return setValue(context, step, context[step.key], value) + }, store) +} + +module.exports = appendField diff --git a/node_modules/append-field/lib/parse-path.js b/node_modules/append-field/lib/parse-path.js new file mode 100644 index 0000000..31d6179 --- /dev/null +++ b/node_modules/append-field/lib/parse-path.js @@ -0,0 +1,53 @@ +var reFirstKey = /^[^\[]*/ +var reDigitPath = /^\[(\d+)\]/ +var reNormalPath = /^\[([^\]]+)\]/ + +function parsePath (key) { + function failure () { + return [{ type: 'object', key: key, last: true }] + } + + var firstKey = reFirstKey.exec(key)[0] + if (!firstKey) return failure() + + var len = key.length + var pos = firstKey.length + var tail = { type: 'object', key: firstKey } + var steps = [tail] + + while (pos < len) { + var m + + if (key[pos] === '[' && key[pos + 1] === ']') { + pos += 2 + tail.append = true + if (pos !== len) return failure() + continue + } + + m = reDigitPath.exec(key.substring(pos)) + if (m !== null) { + pos += m[0].length + tail.nextType = 'array' + tail = { type: 'array', key: parseInt(m[1], 10) } + steps.push(tail) + continue + } + + m = reNormalPath.exec(key.substring(pos)) + if (m !== null) { + pos += m[0].length + tail.nextType = 'object' + tail = { type: 'object', key: m[1] } + steps.push(tail) + continue + } + + return failure() + } + + tail.last = true + return steps +} + +module.exports = parsePath diff --git a/node_modules/append-field/lib/set-value.js b/node_modules/append-field/lib/set-value.js new file mode 100644 index 0000000..c15e873 --- /dev/null +++ b/node_modules/append-field/lib/set-value.js @@ -0,0 +1,64 @@ +function valueType (value) { + if (value === undefined) return 'undefined' + if (Array.isArray(value)) return 'array' + if (typeof value === 'object') return 'object' + return 'scalar' +} + +function setLastValue (context, step, currentValue, entryValue) { + switch (valueType(currentValue)) { + case 'undefined': + if (step.append) { + context[step.key] = [entryValue] + } else { + context[step.key] = entryValue + } + break + case 'array': + context[step.key].push(entryValue) + break + case 'object': + return setLastValue(currentValue, { type: 'object', key: '', last: true }, currentValue[''], entryValue) + case 'scalar': + context[step.key] = [context[step.key], entryValue] + break + } + + return context +} + +function setValue (context, step, currentValue, entryValue) { + if (step.last) return setLastValue(context, step, currentValue, entryValue) + + var obj + switch (valueType(currentValue)) { + case 'undefined': + if (step.nextType === 'array') { + context[step.key] = [] + } else { + context[step.key] = Object.create(null) + } + return context[step.key] + case 'object': + return context[step.key] + case 'array': + if (step.nextType === 'array') { + return currentValue + } + + obj = Object.create(null) + context[step.key] = obj + currentValue.forEach(function (item, i) { + if (item !== undefined) obj['' + i] = item + }) + + return obj + case 'scalar': + obj = Object.create(null) + obj[''] = currentValue + context[step.key] = obj + return obj + } +} + +module.exports = setValue diff --git a/node_modules/append-field/package.json b/node_modules/append-field/package.json new file mode 100644 index 0000000..8d6e716 --- /dev/null +++ b/node_modules/append-field/package.json @@ -0,0 +1,19 @@ +{ + "name": "append-field", + "version": "1.0.0", + "license": "MIT", + "author": "Linus Unnebäck ", + "main": "index.js", + "devDependencies": { + "mocha": "^2.2.4", + "standard": "^6.0.5", + "testdata-w3c-json-form": "^0.2.0" + }, + "scripts": { + "test": "standard && mocha" + }, + "repository": { + "type": "git", + "url": "http://github.com/LinusU/node-append-field.git" + } +} diff --git a/node_modules/append-field/test/forms.js b/node_modules/append-field/test/forms.js new file mode 100644 index 0000000..dd6fbc9 --- /dev/null +++ b/node_modules/append-field/test/forms.js @@ -0,0 +1,19 @@ +/* eslint-env mocha */ + +var assert = require('assert') +var appendField = require('../') +var testData = require('testdata-w3c-json-form') + +describe('Append Field', function () { + for (var test of testData) { + it('handles ' + test.name, function () { + var store = Object.create(null) + + for (var field of test.fields) { + appendField(store, field.key, field.value) + } + + assert.deepEqual(store, test.expected) + }) + } +}) diff --git a/node_modules/asynckit/LICENSE b/node_modules/asynckit/LICENSE new file mode 100644 index 0000000..c9eca5d --- /dev/null +++ b/node_modules/asynckit/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Alex Indigo + +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. diff --git a/node_modules/asynckit/README.md b/node_modules/asynckit/README.md new file mode 100644 index 0000000..ddcc7e6 --- /dev/null +++ b/node_modules/asynckit/README.md @@ -0,0 +1,233 @@ +# asynckit [![NPM Module](https://img.shields.io/npm/v/asynckit.svg?style=flat)](https://www.npmjs.com/package/asynckit) + +Minimal async jobs utility library, with streams support. + +[![PhantomJS Build](https://img.shields.io/travis/alexindigo/asynckit/v0.4.0.svg?label=browser&style=flat)](https://travis-ci.org/alexindigo/asynckit) +[![Linux Build](https://img.shields.io/travis/alexindigo/asynckit/v0.4.0.svg?label=linux:0.12-6.x&style=flat)](https://travis-ci.org/alexindigo/asynckit) +[![Windows Build](https://img.shields.io/appveyor/ci/alexindigo/asynckit/v0.4.0.svg?label=windows:0.12-6.x&style=flat)](https://ci.appveyor.com/project/alexindigo/asynckit) + +[![Coverage Status](https://img.shields.io/coveralls/alexindigo/asynckit/v0.4.0.svg?label=code+coverage&style=flat)](https://coveralls.io/github/alexindigo/asynckit?branch=master) +[![Dependency Status](https://img.shields.io/david/alexindigo/asynckit/v0.4.0.svg?style=flat)](https://david-dm.org/alexindigo/asynckit) +[![bitHound Overall Score](https://www.bithound.io/github/alexindigo/asynckit/badges/score.svg)](https://www.bithound.io/github/alexindigo/asynckit) + + + +AsyncKit provides harness for `parallel` and `serial` iterators over list of items represented by arrays or objects. +Optionally it accepts abort function (should be synchronously return by iterator for each item), and terminates left over jobs upon an error event. For specific iteration order built-in (`ascending` and `descending`) and custom sort helpers also supported, via `asynckit.serialOrdered` method. + +It ensures async operations to keep behavior more stable and prevent `Maximum call stack size exceeded` errors, from sync iterators. + +| compression | size | +| :----------------- | -------: | +| asynckit.js | 12.34 kB | +| asynckit.min.js | 4.11 kB | +| asynckit.min.js.gz | 1.47 kB | + + +## Install + +```sh +$ npm install --save asynckit +``` + +## Examples + +### Parallel Jobs + +Runs iterator over provided array in parallel. Stores output in the `result` array, +on the matching positions. In unlikely event of an error from one of the jobs, +will terminate rest of the active jobs (if abort function is provided) +and return error along with salvaged data to the main callback function. + +#### Input Array + +```javascript +var parallel = require('asynckit').parallel + , assert = require('assert') + ; + +var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ] + , expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ] + , expectedTarget = [ 1, 1, 2, 4, 8, 16, 32, 64 ] + , target = [] + ; + +parallel(source, asyncJob, function(err, result) +{ + assert.deepEqual(result, expectedResult); + assert.deepEqual(target, expectedTarget); +}); + +// async job accepts one element from the array +// and a callback function +function asyncJob(item, cb) +{ + // different delays (in ms) per item + var delay = item * 25; + + // pretend different jobs take different time to finish + // and not in consequential order + var timeoutId = setTimeout(function() { + target.push(item); + cb(null, item * 2); + }, delay); + + // allow to cancel "leftover" jobs upon error + // return function, invoking of which will abort this job + return clearTimeout.bind(null, timeoutId); +} +``` + +More examples could be found in [test/test-parallel-array.js](test/test-parallel-array.js). + +#### Input Object + +Also it supports named jobs, listed via object. + +```javascript +var parallel = require('asynckit/parallel') + , assert = require('assert') + ; + +var source = { first: 1, one: 1, four: 4, sixteen: 16, sixtyFour: 64, thirtyTwo: 32, eight: 8, two: 2 } + , expectedResult = { first: 2, one: 2, four: 8, sixteen: 32, sixtyFour: 128, thirtyTwo: 64, eight: 16, two: 4 } + , expectedTarget = [ 1, 1, 2, 4, 8, 16, 32, 64 ] + , expectedKeys = [ 'first', 'one', 'two', 'four', 'eight', 'sixteen', 'thirtyTwo', 'sixtyFour' ] + , target = [] + , keys = [] + ; + +parallel(source, asyncJob, function(err, result) +{ + assert.deepEqual(result, expectedResult); + assert.deepEqual(target, expectedTarget); + assert.deepEqual(keys, expectedKeys); +}); + +// supports full value, key, callback (shortcut) interface +function asyncJob(item, key, cb) +{ + // different delays (in ms) per item + var delay = item * 25; + + // pretend different jobs take different time to finish + // and not in consequential order + var timeoutId = setTimeout(function() { + keys.push(key); + target.push(item); + cb(null, item * 2); + }, delay); + + // allow to cancel "leftover" jobs upon error + // return function, invoking of which will abort this job + return clearTimeout.bind(null, timeoutId); +} +``` + +More examples could be found in [test/test-parallel-object.js](test/test-parallel-object.js). + +### Serial Jobs + +Runs iterator over provided array sequentially. Stores output in the `result` array, +on the matching positions. In unlikely event of an error from one of the jobs, +will not proceed to the rest of the items in the list +and return error along with salvaged data to the main callback function. + +#### Input Array + +```javascript +var serial = require('asynckit/serial') + , assert = require('assert') + ; + +var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ] + , expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ] + , expectedTarget = [ 0, 1, 2, 3, 4, 5, 6, 7 ] + , target = [] + ; + +serial(source, asyncJob, function(err, result) +{ + assert.deepEqual(result, expectedResult); + assert.deepEqual(target, expectedTarget); +}); + +// extended interface (item, key, callback) +// also supported for arrays +function asyncJob(item, key, cb) +{ + target.push(key); + + // it will be automatically made async + // even it iterator "returns" in the same event loop + cb(null, item * 2); +} +``` + +More examples could be found in [test/test-serial-array.js](test/test-serial-array.js). + +#### Input Object + +Also it supports named jobs, listed via object. + +```javascript +var serial = require('asynckit').serial + , assert = require('assert') + ; + +var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ] + , expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ] + , expectedTarget = [ 0, 1, 2, 3, 4, 5, 6, 7 ] + , target = [] + ; + +var source = { first: 1, one: 1, four: 4, sixteen: 16, sixtyFour: 64, thirtyTwo: 32, eight: 8, two: 2 } + , expectedResult = { first: 2, one: 2, four: 8, sixteen: 32, sixtyFour: 128, thirtyTwo: 64, eight: 16, two: 4 } + , expectedTarget = [ 1, 1, 4, 16, 64, 32, 8, 2 ] + , target = [] + ; + + +serial(source, asyncJob, function(err, result) +{ + assert.deepEqual(result, expectedResult); + assert.deepEqual(target, expectedTarget); +}); + +// shortcut interface (item, callback) +// works for object as well as for the arrays +function asyncJob(item, cb) +{ + target.push(item); + + // it will be automatically made async + // even it iterator "returns" in the same event loop + cb(null, item * 2); +} +``` + +More examples could be found in [test/test-serial-object.js](test/test-serial-object.js). + +_Note: Since _object_ is an _unordered_ collection of properties, +it may produce unexpected results with sequential iterations. +Whenever order of the jobs' execution is important please use `serialOrdered` method._ + +### Ordered Serial Iterations + +TBD + +For example [compare-property](compare-property) package. + +### Streaming interface + +TBD + +## Want to Know More? + +More examples can be found in [test folder](test/). + +Or open an [issue](https://github.com/alexindigo/asynckit/issues) with questions and/or suggestions. + +## License + +AsyncKit is licensed under the MIT license. diff --git a/node_modules/asynckit/bench.js b/node_modules/asynckit/bench.js new file mode 100644 index 0000000..c612f1a --- /dev/null +++ b/node_modules/asynckit/bench.js @@ -0,0 +1,76 @@ +/* eslint no-console: "off" */ + +var asynckit = require('./') + , async = require('async') + , assert = require('assert') + , expected = 0 + ; + +var Benchmark = require('benchmark'); +var suite = new Benchmark.Suite; + +var source = []; +for (var z = 1; z < 100; z++) +{ + source.push(z); + expected += z; +} + +suite +// add tests + +.add('async.map', function(deferred) +{ + var total = 0; + + async.map(source, + function(i, cb) + { + setImmediate(function() + { + total += i; + cb(null, total); + }); + }, + function(err, result) + { + assert.ifError(err); + assert.equal(result[result.length - 1], expected); + deferred.resolve(); + }); +}, {'defer': true}) + + +.add('asynckit.parallel', function(deferred) +{ + var total = 0; + + asynckit.parallel(source, + function(i, cb) + { + setImmediate(function() + { + total += i; + cb(null, total); + }); + }, + function(err, result) + { + assert.ifError(err); + assert.equal(result[result.length - 1], expected); + deferred.resolve(); + }); +}, {'defer': true}) + + +// add listeners +.on('cycle', function(ev) +{ + console.log(String(ev.target)); +}) +.on('complete', function() +{ + console.log('Fastest is ' + this.filter('fastest').map('name')); +}) +// run async +.run({ 'async': true }); diff --git a/node_modules/asynckit/index.js b/node_modules/asynckit/index.js new file mode 100644 index 0000000..455f945 --- /dev/null +++ b/node_modules/asynckit/index.js @@ -0,0 +1,6 @@ +module.exports = +{ + parallel : require('./parallel.js'), + serial : require('./serial.js'), + serialOrdered : require('./serialOrdered.js') +}; diff --git a/node_modules/asynckit/lib/abort.js b/node_modules/asynckit/lib/abort.js new file mode 100644 index 0000000..114367e --- /dev/null +++ b/node_modules/asynckit/lib/abort.js @@ -0,0 +1,29 @@ +// API +module.exports = abort; + +/** + * Aborts leftover active jobs + * + * @param {object} state - current state object + */ +function abort(state) +{ + Object.keys(state.jobs).forEach(clean.bind(state)); + + // reset leftover jobs + state.jobs = {}; +} + +/** + * Cleans up leftover job by invoking abort function for the provided job id + * + * @this state + * @param {string|number} key - job id to abort + */ +function clean(key) +{ + if (typeof this.jobs[key] == 'function') + { + this.jobs[key](); + } +} diff --git a/node_modules/asynckit/lib/async.js b/node_modules/asynckit/lib/async.js new file mode 100644 index 0000000..7f1288a --- /dev/null +++ b/node_modules/asynckit/lib/async.js @@ -0,0 +1,34 @@ +var defer = require('./defer.js'); + +// API +module.exports = async; + +/** + * Runs provided callback asynchronously + * even if callback itself is not + * + * @param {function} callback - callback to invoke + * @returns {function} - augmented callback + */ +function async(callback) +{ + var isAsync = false; + + // check if async happened + defer(function() { isAsync = true; }); + + return function async_callback(err, result) + { + if (isAsync) + { + callback(err, result); + } + else + { + defer(function nextTick_callback() + { + callback(err, result); + }); + } + }; +} diff --git a/node_modules/asynckit/lib/defer.js b/node_modules/asynckit/lib/defer.js new file mode 100644 index 0000000..b67110c --- /dev/null +++ b/node_modules/asynckit/lib/defer.js @@ -0,0 +1,26 @@ +module.exports = defer; + +/** + * Runs provided function on next iteration of the event loop + * + * @param {function} fn - function to run + */ +function defer(fn) +{ + var nextTick = typeof setImmediate == 'function' + ? setImmediate + : ( + typeof process == 'object' && typeof process.nextTick == 'function' + ? process.nextTick + : null + ); + + if (nextTick) + { + nextTick(fn); + } + else + { + setTimeout(fn, 0); + } +} diff --git a/node_modules/asynckit/lib/iterate.js b/node_modules/asynckit/lib/iterate.js new file mode 100644 index 0000000..5d2839a --- /dev/null +++ b/node_modules/asynckit/lib/iterate.js @@ -0,0 +1,75 @@ +var async = require('./async.js') + , abort = require('./abort.js') + ; + +// API +module.exports = iterate; + +/** + * Iterates over each job object + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {object} state - current job status + * @param {function} callback - invoked when all elements processed + */ +function iterate(list, iterator, state, callback) +{ + // store current index + var key = state['keyedList'] ? state['keyedList'][state.index] : state.index; + + state.jobs[key] = runJob(iterator, key, list[key], function(error, output) + { + // don't repeat yourself + // skip secondary callbacks + if (!(key in state.jobs)) + { + return; + } + + // clean up jobs + delete state.jobs[key]; + + if (error) + { + // don't process rest of the results + // stop still active jobs + // and reset the list + abort(state); + } + else + { + state.results[key] = output; + } + + // return salvaged results + callback(error, state.results); + }); +} + +/** + * Runs iterator over provided job element + * + * @param {function} iterator - iterator to invoke + * @param {string|number} key - key/index of the element in the list of jobs + * @param {mixed} item - job description + * @param {function} callback - invoked after iterator is done with the job + * @returns {function|mixed} - job abort function or something else + */ +function runJob(iterator, key, item, callback) +{ + var aborter; + + // allow shortcut if iterator expects only two arguments + if (iterator.length == 2) + { + aborter = iterator(item, async(callback)); + } + // otherwise go with full three arguments + else + { + aborter = iterator(item, key, async(callback)); + } + + return aborter; +} diff --git a/node_modules/asynckit/lib/readable_asynckit.js b/node_modules/asynckit/lib/readable_asynckit.js new file mode 100644 index 0000000..78ad240 --- /dev/null +++ b/node_modules/asynckit/lib/readable_asynckit.js @@ -0,0 +1,91 @@ +var streamify = require('./streamify.js') + , defer = require('./defer.js') + ; + +// API +module.exports = ReadableAsyncKit; + +/** + * Base constructor for all streams + * used to hold properties/methods + */ +function ReadableAsyncKit() +{ + ReadableAsyncKit.super_.apply(this, arguments); + + // list of active jobs + this.jobs = {}; + + // add stream methods + this.destroy = destroy; + this._start = _start; + this._read = _read; +} + +/** + * Destroys readable stream, + * by aborting outstanding jobs + * + * @returns {void} + */ +function destroy() +{ + if (this.destroyed) + { + return; + } + + this.destroyed = true; + + if (typeof this.terminator == 'function') + { + this.terminator(); + } +} + +/** + * Starts provided jobs in async manner + * + * @private + */ +function _start() +{ + // first argument – runner function + var runner = arguments[0] + // take away first argument + , args = Array.prototype.slice.call(arguments, 1) + // second argument - input data + , input = args[0] + // last argument - result callback + , endCb = streamify.callback.call(this, args[args.length - 1]) + ; + + args[args.length - 1] = endCb; + // third argument - iterator + args[1] = streamify.iterator.call(this, args[1]); + + // allow time for proper setup + defer(function() + { + if (!this.destroyed) + { + this.terminator = runner.apply(null, args); + } + else + { + endCb(null, Array.isArray(input) ? [] : {}); + } + }.bind(this)); +} + + +/** + * Implement _read to comply with Readable streams + * Doesn't really make sense for flowing object mode + * + * @private + */ +function _read() +{ + +} diff --git a/node_modules/asynckit/lib/readable_parallel.js b/node_modules/asynckit/lib/readable_parallel.js new file mode 100644 index 0000000..5d2929f --- /dev/null +++ b/node_modules/asynckit/lib/readable_parallel.js @@ -0,0 +1,25 @@ +var parallel = require('../parallel.js'); + +// API +module.exports = ReadableParallel; + +/** + * Streaming wrapper to `asynckit.parallel` + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {stream.Readable#} + */ +function ReadableParallel(list, iterator, callback) +{ + if (!(this instanceof ReadableParallel)) + { + return new ReadableParallel(list, iterator, callback); + } + + // turn on object mode + ReadableParallel.super_.call(this, {objectMode: true}); + + this._start(parallel, list, iterator, callback); +} diff --git a/node_modules/asynckit/lib/readable_serial.js b/node_modules/asynckit/lib/readable_serial.js new file mode 100644 index 0000000..7822698 --- /dev/null +++ b/node_modules/asynckit/lib/readable_serial.js @@ -0,0 +1,25 @@ +var serial = require('../serial.js'); + +// API +module.exports = ReadableSerial; + +/** + * Streaming wrapper to `asynckit.serial` + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {stream.Readable#} + */ +function ReadableSerial(list, iterator, callback) +{ + if (!(this instanceof ReadableSerial)) + { + return new ReadableSerial(list, iterator, callback); + } + + // turn on object mode + ReadableSerial.super_.call(this, {objectMode: true}); + + this._start(serial, list, iterator, callback); +} diff --git a/node_modules/asynckit/lib/readable_serial_ordered.js b/node_modules/asynckit/lib/readable_serial_ordered.js new file mode 100644 index 0000000..3de89c4 --- /dev/null +++ b/node_modules/asynckit/lib/readable_serial_ordered.js @@ -0,0 +1,29 @@ +var serialOrdered = require('../serialOrdered.js'); + +// API +module.exports = ReadableSerialOrdered; +// expose sort helpers +module.exports.ascending = serialOrdered.ascending; +module.exports.descending = serialOrdered.descending; + +/** + * Streaming wrapper to `asynckit.serialOrdered` + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} sortMethod - custom sort function + * @param {function} callback - invoked when all elements processed + * @returns {stream.Readable#} + */ +function ReadableSerialOrdered(list, iterator, sortMethod, callback) +{ + if (!(this instanceof ReadableSerialOrdered)) + { + return new ReadableSerialOrdered(list, iterator, sortMethod, callback); + } + + // turn on object mode + ReadableSerialOrdered.super_.call(this, {objectMode: true}); + + this._start(serialOrdered, list, iterator, sortMethod, callback); +} diff --git a/node_modules/asynckit/lib/state.js b/node_modules/asynckit/lib/state.js new file mode 100644 index 0000000..cbea7ad --- /dev/null +++ b/node_modules/asynckit/lib/state.js @@ -0,0 +1,37 @@ +// API +module.exports = state; + +/** + * Creates initial state object + * for iteration over list + * + * @param {array|object} list - list to iterate over + * @param {function|null} sortMethod - function to use for keys sort, + * or `null` to keep them as is + * @returns {object} - initial state object + */ +function state(list, sortMethod) +{ + var isNamedList = !Array.isArray(list) + , initState = + { + index : 0, + keyedList: isNamedList || sortMethod ? Object.keys(list) : null, + jobs : {}, + results : isNamedList ? {} : [], + size : isNamedList ? Object.keys(list).length : list.length + } + ; + + if (sortMethod) + { + // sort array keys based on it's values + // sort object's keys just on own merit + initState.keyedList.sort(isNamedList ? sortMethod : function(a, b) + { + return sortMethod(list[a], list[b]); + }); + } + + return initState; +} diff --git a/node_modules/asynckit/lib/streamify.js b/node_modules/asynckit/lib/streamify.js new file mode 100644 index 0000000..f56a1c9 --- /dev/null +++ b/node_modules/asynckit/lib/streamify.js @@ -0,0 +1,141 @@ +var async = require('./async.js'); + +// API +module.exports = { + iterator: wrapIterator, + callback: wrapCallback +}; + +/** + * Wraps iterators with long signature + * + * @this ReadableAsyncKit# + * @param {function} iterator - function to wrap + * @returns {function} - wrapped function + */ +function wrapIterator(iterator) +{ + var stream = this; + + return function(item, key, cb) + { + var aborter + , wrappedCb = async(wrapIteratorCallback.call(stream, cb, key)) + ; + + stream.jobs[key] = wrappedCb; + + // it's either shortcut (item, cb) + if (iterator.length == 2) + { + aborter = iterator(item, wrappedCb); + } + // or long format (item, key, cb) + else + { + aborter = iterator(item, key, wrappedCb); + } + + return aborter; + }; +} + +/** + * Wraps provided callback function + * allowing to execute snitch function before + * real callback + * + * @this ReadableAsyncKit# + * @param {function} callback - function to wrap + * @returns {function} - wrapped function + */ +function wrapCallback(callback) +{ + var stream = this; + + var wrapped = function(error, result) + { + return finisher.call(stream, error, result, callback); + }; + + return wrapped; +} + +/** + * Wraps provided iterator callback function + * makes sure snitch only called once, + * but passes secondary calls to the original callback + * + * @this ReadableAsyncKit# + * @param {function} callback - callback to wrap + * @param {number|string} key - iteration key + * @returns {function} wrapped callback + */ +function wrapIteratorCallback(callback, key) +{ + var stream = this; + + return function(error, output) + { + // don't repeat yourself + if (!(key in stream.jobs)) + { + callback(error, output); + return; + } + + // clean up jobs + delete stream.jobs[key]; + + return streamer.call(stream, error, {key: key, value: output}, callback); + }; +} + +/** + * Stream wrapper for iterator callback + * + * @this ReadableAsyncKit# + * @param {mixed} error - error response + * @param {mixed} output - iterator output + * @param {function} callback - callback that expects iterator results + */ +function streamer(error, output, callback) +{ + if (error && !this.error) + { + this.error = error; + this.pause(); + this.emit('error', error); + // send back value only, as expected + callback(error, output && output.value); + return; + } + + // stream stuff + this.push(output); + + // back to original track + // send back value only, as expected + callback(error, output && output.value); +} + +/** + * Stream wrapper for finishing callback + * + * @this ReadableAsyncKit# + * @param {mixed} error - error response + * @param {mixed} output - iterator output + * @param {function} callback - callback that expects final results + */ +function finisher(error, output, callback) +{ + // signal end of the stream + // only for successfully finished streams + if (!error) + { + this.push(null); + } + + // back to original track + callback(error, output); +} diff --git a/node_modules/asynckit/lib/terminator.js b/node_modules/asynckit/lib/terminator.js new file mode 100644 index 0000000..d6eb992 --- /dev/null +++ b/node_modules/asynckit/lib/terminator.js @@ -0,0 +1,29 @@ +var abort = require('./abort.js') + , async = require('./async.js') + ; + +// API +module.exports = terminator; + +/** + * Terminates jobs in the attached state context + * + * @this AsyncKitState# + * @param {function} callback - final callback to invoke after termination + */ +function terminator(callback) +{ + if (!Object.keys(this.jobs).length) + { + return; + } + + // fast forward iteration index + this.index = this.size; + + // abort jobs + abort(this); + + // send back results we have so far + async(callback)(null, this.results); +} diff --git a/node_modules/asynckit/package.json b/node_modules/asynckit/package.json new file mode 100644 index 0000000..51147d6 --- /dev/null +++ b/node_modules/asynckit/package.json @@ -0,0 +1,63 @@ +{ + "name": "asynckit", + "version": "0.4.0", + "description": "Minimal async jobs utility library, with streams support", + "main": "index.js", + "scripts": { + "clean": "rimraf coverage", + "lint": "eslint *.js lib/*.js test/*.js", + "test": "istanbul cover --reporter=json tape -- 'test/test-*.js' | tap-spec", + "win-test": "tape test/test-*.js", + "browser": "browserify -t browserify-istanbul test/lib/browserify_adjustment.js test/test-*.js | obake --coverage | tap-spec", + "report": "istanbul report", + "size": "browserify index.js | size-table asynckit", + "debug": "tape test/test-*.js" + }, + "pre-commit": [ + "clean", + "lint", + "test", + "browser", + "report", + "size" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/alexindigo/asynckit.git" + }, + "keywords": [ + "async", + "jobs", + "parallel", + "serial", + "iterator", + "array", + "object", + "stream", + "destroy", + "terminate", + "abort" + ], + "author": "Alex Indigo ", + "license": "MIT", + "bugs": { + "url": "https://github.com/alexindigo/asynckit/issues" + }, + "homepage": "https://github.com/alexindigo/asynckit#readme", + "devDependencies": { + "browserify": "^13.0.0", + "browserify-istanbul": "^2.0.0", + "coveralls": "^2.11.9", + "eslint": "^2.9.0", + "istanbul": "^0.4.3", + "obake": "^0.1.2", + "phantomjs-prebuilt": "^2.1.7", + "pre-commit": "^1.1.3", + "reamde": "^1.1.0", + "rimraf": "^2.5.2", + "size-table": "^0.2.0", + "tap-spec": "^4.1.1", + "tape": "^4.5.1" + }, + "dependencies": {} +} diff --git a/node_modules/asynckit/parallel.js b/node_modules/asynckit/parallel.js new file mode 100644 index 0000000..3c50344 --- /dev/null +++ b/node_modules/asynckit/parallel.js @@ -0,0 +1,43 @@ +var iterate = require('./lib/iterate.js') + , initState = require('./lib/state.js') + , terminator = require('./lib/terminator.js') + ; + +// Public API +module.exports = parallel; + +/** + * Runs iterator over provided array elements in parallel + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function parallel(list, iterator, callback) +{ + var state = initState(list); + + while (state.index < (state['keyedList'] || list).length) + { + iterate(list, iterator, state, function(error, result) + { + if (error) + { + callback(error, result); + return; + } + + // looks like it's the last one + if (Object.keys(state.jobs).length === 0) + { + callback(null, state.results); + return; + } + }); + + state.index++; + } + + return terminator.bind(state, callback); +} diff --git a/node_modules/asynckit/serial.js b/node_modules/asynckit/serial.js new file mode 100644 index 0000000..6cd949a --- /dev/null +++ b/node_modules/asynckit/serial.js @@ -0,0 +1,17 @@ +var serialOrdered = require('./serialOrdered.js'); + +// Public API +module.exports = serial; + +/** + * Runs iterator over provided array elements in series + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function serial(list, iterator, callback) +{ + return serialOrdered(list, iterator, null, callback); +} diff --git a/node_modules/asynckit/serialOrdered.js b/node_modules/asynckit/serialOrdered.js new file mode 100644 index 0000000..607eafe --- /dev/null +++ b/node_modules/asynckit/serialOrdered.js @@ -0,0 +1,75 @@ +var iterate = require('./lib/iterate.js') + , initState = require('./lib/state.js') + , terminator = require('./lib/terminator.js') + ; + +// Public API +module.exports = serialOrdered; +// sorting helpers +module.exports.ascending = ascending; +module.exports.descending = descending; + +/** + * Runs iterator over provided sorted array elements in series + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} sortMethod - custom sort function + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function serialOrdered(list, iterator, sortMethod, callback) +{ + var state = initState(list, sortMethod); + + iterate(list, iterator, state, function iteratorHandler(error, result) + { + if (error) + { + callback(error, result); + return; + } + + state.index++; + + // are we there yet? + if (state.index < (state['keyedList'] || list).length) + { + iterate(list, iterator, state, iteratorHandler); + return; + } + + // done here + callback(null, state.results); + }); + + return terminator.bind(state, callback); +} + +/* + * -- Sort methods + */ + +/** + * sort helper to sort array elements in ascending order + * + * @param {mixed} a - an item to compare + * @param {mixed} b - an item to compare + * @returns {number} - comparison result + */ +function ascending(a, b) +{ + return a < b ? -1 : a > b ? 1 : 0; +} + +/** + * sort helper to sort array elements in descending order + * + * @param {mixed} a - an item to compare + * @param {mixed} b - an item to compare + * @returns {number} - comparison result + */ +function descending(a, b) +{ + return -1 * ascending(a, b); +} diff --git a/node_modules/asynckit/stream.js b/node_modules/asynckit/stream.js new file mode 100644 index 0000000..d43465f --- /dev/null +++ b/node_modules/asynckit/stream.js @@ -0,0 +1,21 @@ +var inherits = require('util').inherits + , Readable = require('stream').Readable + , ReadableAsyncKit = require('./lib/readable_asynckit.js') + , ReadableParallel = require('./lib/readable_parallel.js') + , ReadableSerial = require('./lib/readable_serial.js') + , ReadableSerialOrdered = require('./lib/readable_serial_ordered.js') + ; + +// API +module.exports = +{ + parallel : ReadableParallel, + serial : ReadableSerial, + serialOrdered : ReadableSerialOrdered, +}; + +inherits(ReadableAsyncKit, Readable); + +inherits(ReadableParallel, ReadableAsyncKit); +inherits(ReadableSerial, ReadableAsyncKit); +inherits(ReadableSerialOrdered, ReadableAsyncKit); diff --git a/node_modules/body-parser/LICENSE b/node_modules/body-parser/LICENSE new file mode 100644 index 0000000..386b7b6 --- /dev/null +++ b/node_modules/body-parser/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2014-2015 Douglas Christopher Wilson + +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. diff --git a/node_modules/body-parser/README.md b/node_modules/body-parser/README.md new file mode 100644 index 0000000..335743d --- /dev/null +++ b/node_modules/body-parser/README.md @@ -0,0 +1,509 @@ +# body-parser + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] +[![OpenSSF Scorecard Badge][ossf-scorecard-badge]][ossf-scorecard-visualizer] + +Node.js body parsing middleware. + +Parse incoming request bodies in a middleware before your handlers, available +under the `req.body` property. + +**Note** As `req.body`'s shape is based on user-controlled input, all +properties and values in this object are untrusted and should be validated +before trusting. For example, `req.body.foo.toString()` may fail in multiple +ways, for example the `foo` property may not be there or may not be a string, +and `toString` may not be a function and instead a string or other user input. + +[Learn about the anatomy of an HTTP transaction in Node.js](https://nodejs.org/en/learn/http/anatomy-of-an-http-transaction). + +_This does not handle multipart bodies_, due to their complex and typically +large nature. For multipart bodies, you may be interested in the following +modules: + + * [busboy](https://www.npmjs.com/package/busboy#readme) and + [connect-busboy](https://www.npmjs.com/package/connect-busboy#readme) + * [multiparty](https://www.npmjs.com/package/multiparty#readme) and + [connect-multiparty](https://www.npmjs.com/package/connect-multiparty#readme) + * [formidable](https://www.npmjs.com/package/formidable#readme) + * [multer](https://www.npmjs.com/package/multer#readme) + +This module provides the following parsers: + + * [JSON body parser](#bodyparserjsonoptions) + * [Raw body parser](#bodyparserrawoptions) + * [Text body parser](#bodyparsertextoptions) + * [URL-encoded form body parser](#bodyparserurlencodedoptions) + +Other body parsers you might be interested in: + +- [body](https://www.npmjs.com/package/body#readme) +- [co-body](https://www.npmjs.com/package/co-body#readme) + +## Installation + +```sh +$ npm install body-parser +``` + +## API + +```js +// Import all parsers +const bodyParser = require('body-parser') + +// Or import individual parsers directly +const json = require('body-parser/json') +const urlencoded = require('body-parser/urlencoded') +const raw = require('body-parser/raw') +const text = require('body-parser/text') +``` + +The `bodyParser` object exposes various factories to create middlewares. All +middlewares will populate the `req.body` property with the parsed body when +the `Content-Type` request header matches the `type` option. + +The various errors returned by this module are described in the +[errors section](#errors). + +### bodyParser.json([options]) + +Returns middleware that only parses `json` and only looks at requests where +the `Content-Type` header matches the `type` option. This parser accepts any +Unicode encoding of the body and supports automatic inflation of `gzip`, +`br` (brotli) and `deflate` encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). + +#### Options + +The `json` function takes an optional `options` object that may contain any of +the following keys: + +##### defaultCharset + +Specify the default character set for the json content if the charset is not +specified in the `Content-Type` header of the request. Defaults to `utf-8`. + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +> It’s recommended not to configure a very high limit and to use the default value whenever possible. Allowing larger payloads increases memory usage because of the resources required for decoding and transformations, and it can also lead to longer response times as more data is processed. By ‘very high’, we mean values above the default, for example payloads of 5 MB or more can already start to introduce these risks. With the default limits, these issues do not occur. + +##### reviver + +The `reviver` option is passed directly to `JSON.parse` as the second +argument. You can find more information on this argument +[in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#the_reviver_parameter). + +##### strict + +When set to `true`, will only accept arrays and objects; when `false` will +accept anything `JSON.parse` accepts. Defaults to `true`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. If not a +function, `type` option is passed directly to the +[type-is](https://www.npmjs.com/package/type-is#readme) library and this can +be an extension name (like `json`), a mime type (like `application/json`), or +a mime type with a wildcard (like `*/*` or `*/json`). If a function, the `type` +option is called as `fn(req)` and the request is parsed if it returns a truthy +value. Defaults to `application/json`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.raw([options]) + +Returns middleware that parses all bodies as a `Buffer` and only looks at +requests where the `Content-Type` header matches the `type` option. This +parser supports automatic inflation of `gzip`, `br` (brotli) and `deflate` +encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This will be a `Buffer` object +of the body. + +#### Options + +The `raw` function takes an optional `options` object that may contain any of +the following keys: + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +> It’s recommended not to configure a very high limit and to use the default value whenever possible. Allowing larger payloads increases memory usage because of the resources required for decoding and transformations, and it can also lead to longer response times as more data is processed. By ‘very high’, we mean values above the default, for example payloads of 5 MB or more can already start to introduce these risks. With the default limits, these issues do not occur. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. +If not a function, `type` option is passed directly to the +[type-is](https://www.npmjs.com/package/type-is#readme) library and this +can be an extension name (like `bin`), a mime type (like +`application/octet-stream`), or a mime type with a wildcard (like `*/*` or +`application/*`). If a function, the `type` option is called as `fn(req)` +and the request is parsed if it returns a truthy value. Defaults to +`application/octet-stream`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.text([options]) + +Returns middleware that parses all bodies as a string and only looks at +requests where the `Content-Type` header matches the `type` option. This +parser supports automatic inflation of `gzip`, `br` (brotli) and `deflate` +encodings. + +A new `body` string containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This will be a string of the +body. + +#### Options + +The `text` function takes an optional `options` object that may contain any of +the following keys: + +##### defaultCharset + +Specify the default character set for the text content if the charset is not +specified in the `Content-Type` header of the request. Defaults to `utf-8`. + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +> It’s recommended not to configure a very high limit and to use the default value whenever possible. Allowing larger payloads increases memory usage because of the resources required for decoding and transformations, and it can also lead to longer response times as more data is processed. By ‘very high’, we mean values above the default, for example payloads of 5 MB or more can already start to introduce these risks. With the default limits, these issues do not occur. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. If not +a function, `type` option is passed directly to the +[type-is](https://www.npmjs.com/package/type-is#readme) library and this can +be an extension name (like `txt`), a mime type (like `text/plain`), or a mime +type with a wildcard (like `*/*` or `text/*`). If a function, the `type` +option is called as `fn(req)` and the request is parsed if it returns a +truthy value. Defaults to `text/plain`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.urlencoded([options]) + +Returns middleware that only parses `urlencoded` bodies and only looks at +requests where the `Content-Type` header matches the `type` option. This +parser accepts only UTF-8 and ISO-8859-1 encodings of the body and supports +automatic inflation of `gzip`, `br` (brotli) and `deflate` encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This object will contain +key-value pairs, where the value can be a string or array (when `extended` is +`false`), or any type (when `extended` is `true`). + +#### Options + +The `urlencoded` function takes an optional `options` object that may contain +any of the following keys: + +##### extended + +The "extended" syntax allows for rich objects and arrays to be encoded into the +URL-encoded format, allowing for a JSON-like experience with URL-encoded. For +more information, please [see the qs +library](https://www.npmjs.com/package/qs#readme). + +Defaults to `false`. + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +> It’s recommended not to configure a very high limit and to use the default value whenever possible. Allowing larger payloads increases memory usage because of the resources required for decoding and transformations, and it can also lead to longer response times as more data is processed. By ‘very high’, we mean values above the default, for example payloads of 5 MB or more can already start to introduce these risks. With the default limits, these issues do not occur. + +##### parameterLimit + +The `parameterLimit` option controls the maximum number of parameters that +are allowed in the URL-encoded data. If a request contains more parameters +than this value, a 413 will be returned to the client. Defaults to `1000`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. If not +a function, `type` option is passed directly to the +[type-is](https://www.npmjs.com/package/type-is#readme) library and this can +be an extension name (like `urlencoded`), a mime type (like +`application/x-www-form-urlencoded`), or a mime type with a wildcard (like +`*/x-www-form-urlencoded`). If a function, the `type` option is called as +`fn(req)` and the request is parsed if it returns a truthy value. Defaults +to `application/x-www-form-urlencoded`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +##### defaultCharset + +The default charset to parse as, if not specified in content-type. Must be +either `utf-8` or `iso-8859-1`. Defaults to `utf-8`. + +##### charsetSentinel + +Whether to let the value of the `utf8` parameter take precedence as the charset +selector. It requires the form to contain a parameter named `utf8` with a value +of `✓`. Defaults to `false`. + +##### interpretNumericEntities + +Whether to decode numeric entities such as `☺` when parsing an iso-8859-1 +form. Defaults to `false`. + + +##### depth + +The `depth` option is used to configure the maximum depth of the `qs` library when `extended` is `true`. This allows you to limit the amount of keys that are parsed and can be useful to prevent certain types of abuse. Defaults to `32`. It is recommended to keep this value as low as possible. + +## Errors + +The middlewares provided by this module create errors using the +[`http-errors` module](https://www.npmjs.com/package/http-errors). The errors +will typically have a `status`/`statusCode` property that contains the suggested +HTTP response code, an `expose` property to determine if the `message` property +should be displayed to the client, a `type` property to determine the type of +error without matching against the `message`, and a `body` property containing +the read body, if available. + +The following are the common errors created, though any error can come through +for various reasons. + +### content encoding unsupported + +This error will occur when the request had a `Content-Encoding` header that +contained an encoding but the "inflation" option was set to `false`. The +`status` property is set to `415`, the `type` property is set to +`'encoding.unsupported'`, and the `charset` property will be set to the +encoding that is unsupported. + +### entity parse failed + +This error will occur when the request contained an entity that could not be +parsed by the middleware. The `status` property is set to `400`, the `type` +property is set to `'entity.parse.failed'`, and the `body` property is set to +the entity value that failed parsing. + +### entity verify failed + +This error will occur when the request contained an entity that could not be +failed verification by the defined `verify` option. The `status` property is +set to `403`, the `type` property is set to `'entity.verify.failed'`, and the +`body` property is set to the entity value that failed verification. + +### request aborted + +This error will occur when the request is aborted by the client before reading +the body has finished. The `received` property will be set to the number of +bytes received before the request was aborted and the `expected` property is +set to the number of expected bytes. The `status` property is set to `400` +and `type` property is set to `'request.aborted'`. + +### request entity too large + +This error will occur when the request body's size is larger than the "limit" +option. The `limit` property will be set to the byte limit and the `length` +property will be set to the request body's length. The `status` property is +set to `413` and the `type` property is set to `'entity.too.large'`. + +### request size did not match content length + +This error will occur when the request's length did not match the length from +the `Content-Length` header. This typically occurs when the request is malformed, +typically when the `Content-Length` header was calculated based on characters +instead of bytes. The `status` property is set to `400` and the `type` property +is set to `'request.size.invalid'`. + +### stream encoding should not be set + +This error will occur when something called the `req.setEncoding` method prior +to this middleware. This module operates directly on bytes only and you cannot +call `req.setEncoding` when using this module. The `status` property is set to +`500` and the `type` property is set to `'stream.encoding.set'`. + +### stream is not readable + +This error will occur when the request is no longer readable when this middleware +attempts to read it. This typically means something other than a middleware from +this module read the request body already and the middleware was also configured to +read the same request. The `status` property is set to `500` and the `type` +property is set to `'stream.not.readable'`. + +### too many parameters + +This error will occur when the content of the request exceeds the configured +`parameterLimit` for the `urlencoded` parser. The `status` property is set to +`413` and the `type` property is set to `'parameters.too.many'`. + +### unsupported charset "BOGUS" + +This error will occur when the request had a charset parameter in the +`Content-Type` header, but the `iconv-lite` module does not support it OR the +parser does not support it. The charset is contained in the message as well +as in the `charset` property. The `status` property is set to `415`, the +`type` property is set to `'charset.unsupported'`, and the `charset` property +is set to the charset that is unsupported. + +### unsupported content encoding "bogus" + +This error will occur when the request had a `Content-Encoding` header that +contained an unsupported encoding. The encoding is contained in the message +as well as in the `encoding` property. The `status` property is set to `415`, +the `type` property is set to `'encoding.unsupported'`, and the `encoding` +property is set to the encoding that is unsupported. + +### The input exceeded the depth + +This error occurs when using `bodyParser.urlencoded` with the `extended` property set to `true` and the input exceeds the configured `depth` option. The `status` property is set to `400`. It is recommended to review the `depth` option and evaluate if it requires a higher value. When the `depth` option is set to `32` (default value), the error will not be thrown. + +## Examples + +### Express/Connect top-level generic + +This example demonstrates adding a generic JSON and URL-encoded parser as a +top-level middleware, which will parse the bodies of all incoming requests. +This is the simplest setup. + +```js +const express = require('express') +const bodyParser = require('body-parser') + +const app = express() + +// parse application/x-www-form-urlencoded +app.use(bodyParser.urlencoded()) + +// parse application/json +app.use(bodyParser.json()) + +app.use(function (req, res) { + res.setHeader('Content-Type', 'text/plain') + res.write('you posted:\n') + res.end(String(JSON.stringify(req.body, null, 2))) +}) +``` + +### Express route-specific + +This example demonstrates adding body parsers specifically to the routes that +need them. In general, this is the most recommended way to use body-parser with +Express. + +```js +const express = require('express') +const bodyParser = require('body-parser') + +const app = express() + +// create application/json parser +const jsonParser = bodyParser.json() + +// create application/x-www-form-urlencoded parser +const urlencodedParser = bodyParser.urlencoded() + +// POST /login gets urlencoded bodies +app.post('/login', urlencodedParser, function (req, res) { + if (!req.body || !req.body.username) res.sendStatus(400) + res.send('welcome, ' + req.body.username) +}) + +// POST /api/users gets JSON bodies +app.post('/api/users', jsonParser, function (req, res) { + if (!req.body) res.sendStatus(400) + // create user in req.body +}) +``` + +### Change accepted type for parsers + +All the parsers accept a `type` option which allows you to change the +`Content-Type` that the middleware will parse. + +```js +const express = require('express') +const bodyParser = require('body-parser') + +const app = express() + +// parse various different custom JSON types as JSON +app.use(bodyParser.json({ type: 'application/*+json' })) + +// parse some custom thing into a Buffer +app.use(bodyParser.raw({ type: 'application/vnd.custom-type' })) + +// parse an HTML body into a string +app.use(bodyParser.text({ type: 'text/html' })) +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://img.shields.io/github/actions/workflow/status/expressjs/body-parser/ci.yml?branch=master&label=ci +[ci-url]: https://github.com/expressjs/body-parser/actions/workflows/ci.yml +[coveralls-image]: https://img.shields.io/coverallsCoverage/github/expressjs/body-parser?branch=master +[coveralls-url]: https://coveralls.io/r/expressjs/body-parser?branch=master +[npm-downloads-image]: https://img.shields.io/npm/dm/body-parser +[npm-url]: https://npmjs.com/package/body-parser +[npm-version-image]: https://img.shields.io/npm/v/body-parser +[ossf-scorecard-badge]: https://api.scorecard.dev/projects/github.com/expressjs/body-parser/badge +[ossf-scorecard-visualizer]: https://ossf.github.io/scorecard-visualizer/#/projects/github.com/expressjs/body-parser diff --git a/node_modules/body-parser/index.js b/node_modules/body-parser/index.js new file mode 100644 index 0000000..c0526e1 --- /dev/null +++ b/node_modules/body-parser/index.js @@ -0,0 +1,55 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * @typedef {Object} Parsers + * @property {Function} json JSON parser + * @property {Function} raw Raw parser + * @property {Function} text Text parser + * @property {Function} urlencoded URL-encoded parser + */ + +/** + * Module exports. + * @type {Function & Parsers} + */ +exports = module.exports = bodyParser + +/** + * JSON parser. + * @public + */ +exports.json = require('./lib/types/json') + +/** + * Raw parser. + * @public + */ +exports.raw = require('./lib/types/raw') + +/** + * Text parser. + * @public + */ +exports.text = require('./lib/types/text') + +/** + * URL-encoded parser. + * @public + */ +exports.urlencoded = require('./lib/types/urlencoded') + +/** + * Create a middleware to parse json and urlencoded bodies. + * + * @deprecated + * @public + */ +function bodyParser () { + throw new Error('The bodyParser() generic has been split into individual middleware to use instead.') +} diff --git a/node_modules/body-parser/lib/read.js b/node_modules/body-parser/lib/read.js new file mode 100644 index 0000000..bf1a1df --- /dev/null +++ b/node_modules/body-parser/lib/read.js @@ -0,0 +1,247 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +const createError = require('http-errors') +const getBody = require('raw-body') +const iconv = require('iconv-lite') +const onFinished = require('on-finished') +const zlib = require('node:zlib') +const hasBody = require('type-is').hasBody +const { getCharset } = require('./utils') + +/** + * Module exports. + */ + +module.exports = read + +/** + * Read a request into a buffer and parse. + * + * @param {Object} req + * @param {Object} res + * @param {Function} next + * @param {Function} parse + * @param {Function} debug + * @param {Object} options + * @private + */ +function read (req, res, next, parse, debug, options) { + if (onFinished.isFinished(req)) { + debug('body already parsed') + next() + return + } + + if (!('body' in req)) { + req.body = undefined + } + + // skip requests without bodies + if (!hasBody(req)) { + debug('skip empty body') + next() + return + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!options.shouldParse(req)) { + debug('skip parsing') + next() + return + } + + let encoding = null + if (options?.skipCharset !== true) { + encoding = getCharset(req) || options.defaultCharset + + // validate charset + if (!!options?.isValidCharset && !options.isValidCharset(encoding)) { + debug('invalid charset') + next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { + charset: encoding, + type: 'charset.unsupported' + })) + return + } + } + + let length + const opts = options + let stream + + // read options + const verify = opts.verify + + try { + // get the content stream + stream = contentstream(req, debug, opts.inflate) + length = stream.length + stream.length = undefined + } catch (err) { + return next(err) + } + + // set raw-body options + opts.length = length + opts.encoding = verify + ? null + : encoding + + // assert charset is supported + if (opts.encoding === null && encoding !== null && !iconv.encodingExists(encoding)) { + return next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { + charset: encoding.toLowerCase(), + type: 'charset.unsupported' + })) + } + + // read body + debug('read body') + getBody(stream, opts, function (error, body) { + if (error) { + let _error + + if (error.type === 'encoding.unsupported') { + // echo back charset + _error = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { + charset: encoding.toLowerCase(), + type: 'charset.unsupported' + }) + } else { + // set status code on error + _error = createError(400, error) + } + + // unpipe from stream and destroy + if (stream !== req) { + req.unpipe() + stream.destroy() + } + + // read off entire request + dump(req, function onfinished () { + next(createError(400, _error)) + }) + return + } + + // verify + if (verify) { + try { + debug('verify body') + verify(req, res, body, encoding) + } catch (err) { + next(createError(403, err, { + body: body, + type: err.type || 'entity.verify.failed' + })) + return + } + } + + // parse + let str = body + try { + debug('parse body') + str = typeof body !== 'string' && encoding !== null + ? iconv.decode(body, encoding) + : body + req.body = parse(str, encoding) + } catch (err) { + next(createError(400, err, { + body: str, + type: err.type || 'entity.parse.failed' + })) + return + } + + next() + }) +} + +/** + * Get the content stream of the request. + * + * @param {Object} req + * @param {Function} debug + * @param {boolean} inflate + * @returns {Object} + * @private + */ +function contentstream (req, debug, inflate) { + const encoding = (req.headers['content-encoding'] || 'identity').toLowerCase() + const length = req.headers['content-length'] + + debug('content-encoding "%s"', encoding) + + if (inflate === false && encoding !== 'identity') { + throw createError(415, 'content encoding unsupported', { + encoding: encoding, + type: 'encoding.unsupported' + }) + } + + if (encoding === 'identity') { + req.length = length + return req + } + + const stream = createDecompressionStream(encoding, debug) + req.pipe(stream) + return stream +} + +/** + * Create a decompression stream for the given encoding. + * @param {string} encoding + * @param {Function} debug + * @returns {Object} + * @private + */ +function createDecompressionStream (encoding, debug) { + switch (encoding) { + case 'deflate': + debug('inflate body') + return zlib.createInflate() + case 'gzip': + debug('gunzip body') + return zlib.createGunzip() + case 'br': + debug('brotli decompress body') + return zlib.createBrotliDecompress() + default: + throw createError(415, 'unsupported content encoding "' + encoding + '"', { + encoding: encoding, + type: 'encoding.unsupported' + }) + } +} + +/** + * Dump the contents of a request. + * + * @param {Object} req + * @param {Function} callback + * @private + */ +function dump (req, callback) { + if (onFinished.isFinished(req)) { + callback(null) + } else { + onFinished(req, callback) + req.resume() + } +} diff --git a/node_modules/body-parser/lib/types/json.js b/node_modules/body-parser/lib/types/json.js new file mode 100644 index 0000000..14ca3e4 --- /dev/null +++ b/node_modules/body-parser/lib/types/json.js @@ -0,0 +1,186 @@ +/*! + * body-parser + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +const debug = require('debug')('body-parser:json') +const read = require('../read') +const { normalizeOptions } = require('../utils') + +/** + * Module exports. + */ + +module.exports = json + +/** + * RegExp to match the first non-space in a string. + * + * Allowed whitespace is defined in RFC 7159: + * + * ws = *( + * %x20 / ; Space + * %x09 / ; Horizontal tab + * %x0A / ; Line feed or New line + * %x0D ) ; Carriage return + */ +const FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*([^\x20\x09\x0a\x0d])/ // eslint-disable-line no-control-regex + +const JSON_SYNTAX_CHAR = '#' +const JSON_SYNTAX_REGEXP = /#+/g + +/** + * Create a middleware to parse JSON bodies. + * + * @param {Object} [options] + * @returns {Function} + * @public + */ +function json (options) { + const normalizedOptions = normalizeOptions(options, 'application/json') + + const parse = createJsonParser(options) + + const readOptions = { + ...normalizedOptions, + // assert charset per RFC 7159 sec 8.1 + isValidCharset: (charset) => charset.slice(0, 4) === 'utf-' + } + + return function jsonParser (req, res, next) { + read(req, res, next, parse, debug, readOptions) + } +} + +/** + * Create a JSON parse function + * + * @param {object} [options] + * @return {function} + * @private + */ +function createJsonParser (options) { + const reviver = options?.reviver + const strict = options?.strict !== false + + if (strict) { + return function parse (body) { + if (body.length === 0) { + // special-case empty json body, as it's a common client-side mistake + // TODO: maybe make this configurable or part of "strict" option + return {} + } + + const first = firstchar(body) + if (first !== '{' && first !== '[') { + debug('strict violation') + throw createStrictSyntaxError(body, first) + } + + try { + debug('parse json') + return JSON.parse(body, reviver) + } catch (e) { + throw normalizeJsonSyntaxError(e, { + message: e.message, + stack: e.stack + }) + } + } + } + + return function parse (body) { + if (body.length === 0) { + // special-case empty json body, as it's a common client-side mistake + // TODO: maybe make this configurable or part of "strict" option + return {} + } + + try { + debug('parse json') + return JSON.parse(body, reviver) + } catch (e) { + throw normalizeJsonSyntaxError(e, { + message: e.message, + stack: e.stack + }) + } + } +} + +/** + * Create strict violation syntax error matching native error. + * + * @param {string} str + * @param {string} char + * @returns {Error} + * @private + */ +function createStrictSyntaxError (str, char) { + const index = str.indexOf(char) + let partial = '' + + if (index !== -1) { + partial = str.substring(0, index) + JSON_SYNTAX_CHAR.repeat(str.length - index) + } + + try { + JSON.parse(partial); /* istanbul ignore next */ throw new SyntaxError('strict violation') + } catch (e) { + return normalizeJsonSyntaxError(e, { + message: e.message.replace(JSON_SYNTAX_REGEXP, function (placeholder) { + return str.substring(index, index + placeholder.length) + }), + stack: e.stack + }) + } +} + +/** + * Get the first non-whitespace character in a string. + * + * @param {string} str + * @returns {string|undefined} + * @private + */ +function firstchar (str) { + const match = FIRST_CHAR_REGEXP.exec(str) + + return match + ? match[1] + : undefined +} + +/** + * Normalize a SyntaxError for JSON.parse. + * + * @param {SyntaxError} error + * @param {Object} obj + * @returns {SyntaxError} + * @private + */ +function normalizeJsonSyntaxError (error, obj) { + const keys = Object.getOwnPropertyNames(error) + + for (let i = 0; i < keys.length; i++) { + const key = keys[i] + if (key !== 'stack' && key !== 'message') { + delete error[key] + } + } + + // replace stack before message for Node.js 0.10 and below + error.stack = obj.stack.replace(error.message, obj.message) + error.message = obj.message + + return error +} diff --git a/node_modules/body-parser/lib/types/raw.js b/node_modules/body-parser/lib/types/raw.js new file mode 100644 index 0000000..c84083b --- /dev/null +++ b/node_modules/body-parser/lib/types/raw.js @@ -0,0 +1,42 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + */ + +const debug = require('debug')('body-parser:raw') +const read = require('../read') +const { normalizeOptions, passthrough } = require('../utils') + +/** + * Module exports. + */ + +module.exports = raw + +/** + * Create a middleware to parse raw bodies. + * + * @param {Object} [options] + * @returns {Function} + * @public + */ +function raw (options) { + const normalizedOptions = normalizeOptions(options, 'application/octet-stream') + + const readOptions = { + ...normalizedOptions, + // Skip charset validation and parse the body as is + skipCharset: true + } + + return function rawParser (req, res, next) { + read(req, res, next, passthrough, debug, readOptions) + } +} diff --git a/node_modules/body-parser/lib/types/text.js b/node_modules/body-parser/lib/types/text.js new file mode 100644 index 0000000..893c801 --- /dev/null +++ b/node_modules/body-parser/lib/types/text.js @@ -0,0 +1,36 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + */ + +const debug = require('debug')('body-parser:text') +const read = require('../read') +const { normalizeOptions, passthrough } = require('../utils') + +/** + * Module exports. + */ + +module.exports = text + +/** + * Create a middleware to parse text bodies. + * + * @param {Object} [options] + * @returns {Function} + * @public + */ +function text (options) { + const normalizedOptions = normalizeOptions(options, 'text/plain') + + return function textParser (req, res, next) { + read(req, res, next, passthrough, debug, normalizedOptions) + } +} diff --git a/node_modules/body-parser/lib/types/urlencoded.js b/node_modules/body-parser/lib/types/urlencoded.js new file mode 100644 index 0000000..1db964c --- /dev/null +++ b/node_modules/body-parser/lib/types/urlencoded.js @@ -0,0 +1,138 @@ +/*! + * body-parser + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +const createError = require('http-errors') +const debug = require('debug')('body-parser:urlencoded') +const read = require('../read') +const qs = require('qs') +const { normalizeOptions } = require('../utils') + +/** + * Module exports. + */ + +module.exports = urlencoded + +/** + * Create a middleware to parse urlencoded bodies. + * + * @param {Object} [options] + * @returns {Function} + * @public + */ +function urlencoded (options) { + const normalizedOptions = normalizeOptions(options, 'application/x-www-form-urlencoded') + + if (normalizedOptions.defaultCharset !== 'utf-8' && normalizedOptions.defaultCharset !== 'iso-8859-1') { + throw new TypeError('option defaultCharset must be either utf-8 or iso-8859-1') + } + + // create the appropriate query parser + const parse = createQueryParser(options) + + const readOptions = { + ...normalizedOptions, + // assert charset + isValidCharset: (charset) => charset === 'utf-8' || charset === 'iso-8859-1' + } + + return function urlencodedParser (req, res, next) { + read(req, res, next, parse, debug, readOptions) + } +} + +/** + * Get the extended query parser. + * + * @param {Object} options + * @returns {Function} + * @private + */ +function createQueryParser (options) { + const extended = Boolean(options?.extended) + let parameterLimit = options?.parameterLimit !== undefined + ? options?.parameterLimit + : 1000 + const charsetSentinel = options?.charsetSentinel + const interpretNumericEntities = options?.interpretNumericEntities + const depth = extended ? (options?.depth !== undefined ? options?.depth : 32) : 0 + + if (isNaN(parameterLimit) || parameterLimit < 1) { + throw new TypeError('option parameterLimit must be a positive number') + } + + if (isNaN(depth) || depth < 0) { + throw new TypeError('option depth must be a zero or a positive number') + } + + if (isFinite(parameterLimit)) { + parameterLimit = parameterLimit | 0 + } + + return function parse (body, encoding) { + if (!body.length) return {} + + const paramCount = parameterCount(body, parameterLimit) + + if (paramCount === undefined) { + debug('too many parameters') + throw createError(413, 'too many parameters', { + type: 'parameters.too.many' + }) + } + + const arrayLimit = extended ? Math.max(100, paramCount) : paramCount + + debug('parse ' + (extended ? 'extended ' : '') + 'urlencoding') + try { + return qs.parse(body, { + allowPrototypes: true, + arrayLimit: arrayLimit, + depth: depth, + charsetSentinel: charsetSentinel, + interpretNumericEntities: interpretNumericEntities, + charset: encoding, + parameterLimit: parameterLimit, + strictDepth: true + }) + } catch (err) { + if (err instanceof RangeError) { + throw createError(400, 'The input exceeded the depth', { + type: 'querystring.parse.rangeError' + }) + } else { + throw err + } + } + } +} + +/** + * Count the number of parameters, stopping once limit reached + * + * @param {string} body + * @param {number} limit + * @returns {number|undefined} Returns undefined if limit exceeded + * @private + */ +function parameterCount (body, limit) { + let count = 0 + let index = -1 + do { + count++ + if (count > limit) return undefined // Early exit if limit exceeded + index = body.indexOf('&', index + 1) + } while (index !== -1) + return count +} diff --git a/node_modules/body-parser/lib/utils.js b/node_modules/body-parser/lib/utils.js new file mode 100644 index 0000000..7a0dda4 --- /dev/null +++ b/node_modules/body-parser/lib/utils.js @@ -0,0 +1,100 @@ +'use strict' + +/** + * Module dependencies. + */ + +const bytes = require('bytes') +const contentType = require('content-type') +const typeis = require('type-is') + +/** + * Module exports. + */ +module.exports = { + getCharset, + normalizeOptions, + passthrough +} + +/** + * Get the charset of a request. + * + * @param {Object} req + * @returns {string | undefined} + * @private + */ +function getCharset (req) { + const header = req.headers['content-type'] + if (!header) return undefined + return contentType.parse(header).parameters.charset?.toLowerCase() +} + +/** + * Get the simple type checker. + * + * @param {string | string[]} type + * @returns {Function} + * @private + */ +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} + +/** + * Normalizes the common options for all parsers. + * + * @param {Object} options options to normalize + * @param {string | string[] | Function} defaultType default content type(s) or a function to determine it + * @returns {Object} + * @private + */ +function normalizeOptions (options, defaultType) { + if (!defaultType) { + // Parsers must define a default content type + throw new TypeError('defaultType must be provided') + } + + const inflate = options?.inflate !== false + const limit = typeof options?.limit === 'undefined' || options?.limit === null + ? 102400 // 100kb default + : bytes.parse(options.limit) + const type = options?.type || defaultType + const verify = options?.verify || false + const defaultCharset = options?.defaultCharset || 'utf-8' + + if (limit === null) { + throw new TypeError(`option limit "${String(options.limit)}" is invalid`) + } + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate type checking function + const shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + return { + inflate, + limit, + verify, + defaultCharset, + shouldParse + } +} + +/** + * Passthrough function that returns input unchanged. + * Used by parsers that don't need to transform the data. + * + * @param {*} value + * @returns {*} + * @private + */ +function passthrough (value) { + return value +} diff --git a/node_modules/body-parser/node_modules/content-type/LICENSE b/node_modules/body-parser/node_modules/content-type/LICENSE new file mode 100644 index 0000000..34b1a2d --- /dev/null +++ b/node_modules/body-parser/node_modules/content-type/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2015 Douglas Christopher Wilson + +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. diff --git a/node_modules/body-parser/node_modules/content-type/README.md b/node_modules/body-parser/node_modules/content-type/README.md new file mode 100644 index 0000000..ae275e0 --- /dev/null +++ b/node_modules/body-parser/node_modules/content-type/README.md @@ -0,0 +1,71 @@ +# content-type + +[![NPM version][npm-image]][npm-url] +[![NPM downloads][downloads-image]][downloads-url] +[![Build status][build-image]][build-url] +[![Build coverage][coverage-image]][coverage-url] +[![License][license-image]][license-url] + +Create and parse HTTP `Content-Type` header. + +## Installation + +```sh +npm install content-type +``` + +## API + +```js +const contentType = require("content-type"); +``` + +### contentType.parse(string, options?) + +```js +const obj = contentType.parse("image/svg+xml; charset=utf-8"); +``` + +Parse a `Content-Type` header. This will return an object with the following properties (examples are shown for the string `'image/svg+xml; charset=utf-8'`): + +- `type`: The media type. Example: `'image/svg+xml'`. +- `parameters`: An object of the parameters in the media type (parameter name is always lower case). Example: `{charset: 'utf-8'}`. + +The parser is lenient and does not error. You should validate `type` and `parameters` before trusting them. + +#### Options + +- `parameters` (default: `true`): Set to `false` to skip parameters. +- `comma` (default: `false`): Set to `true` to stop on a comma. This can be used to parse the media range in an `Accept` header. +- `start` (default: `0`): Set index to start parsing from. + +### contentType.format(obj) + +```js +const str = contentType.format({ + type: "image/svg+xml", + parameters: { charset: "utf-8" }, +}); +``` + +Format an object into a `Content-Type` header. This will return a string of the content type for the given object with the following properties (examples are shown that produce the string `'image/svg+xml; charset=utf-8'`): + +- `type`: The media type. Example: `'image/svg+xml'`. +- `parameters`: An optional object of the parameters in the media type. Example: `{charset: 'utf-8'}`. + +Throws a `TypeError` if the object contains an invalid type or parameter names. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/content-type +[npm-url]: https://npmjs.org/package/content-type +[downloads-image]: https://img.shields.io/npm/dm/content-type +[downloads-url]: https://npmjs.org/package/content-type +[build-image]: https://img.shields.io/github/actions/workflow/status/jshttp/content-type/ci.yml?branch=master +[build-url]: https://github.com/jshttp/content-type/actions/workflows/ci.yml?query=branch%3Amaster +[coverage-image]: https://img.shields.io/codecov/c/gh/jshttp/content-type +[coverage-url]: https://codecov.io/gh/jshttp/content-type +[license-image]: http://img.shields.io/npm/l/content-type.svg?style=flat +[license-url]: LICENSE diff --git a/node_modules/body-parser/node_modules/content-type/dist/index.d.ts b/node_modules/body-parser/node_modules/content-type/dist/index.d.ts new file mode 100644 index 0000000..c153445 --- /dev/null +++ b/node_modules/body-parser/node_modules/content-type/dist/index.d.ts @@ -0,0 +1,46 @@ +/*! + * content-type + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ +/** + * The content type object contains a type string and optional parameters. + */ +export interface ContentType { + type: string; + index: number; + parameters: Record; +} +/** + * Format an object into a `Content-Type` header. + */ +export declare function format(obj: Partial): string; +/** + * Options for parsing a `Content-Type` header. + */ +export interface ParseOptions { + /** + * Exit early on the first semicolon, returning only the type. + * This is useful for parsing the MIME from `Content-Type` headers. + * + * @default false + */ + parameters?: boolean; + /** + * Exits early on a comma, returning the first value and parameters. + * This is useful for parsing `Accept` headers. + * + * @default false + */ + comma?: boolean; + /** + * The index to start parsing from. + * + * @default 0 + */ + start?: number; +} +/** + * Parse a `Content-Type` header. + */ +export declare function parse(header: string, options?: ParseOptions): ContentType; diff --git a/node_modules/body-parser/node_modules/content-type/dist/index.js b/node_modules/body-parser/node_modules/content-type/dist/index.js new file mode 100644 index 0000000..6f3a3e7 --- /dev/null +++ b/node_modules/body-parser/node_modules/content-type/dist/index.js @@ -0,0 +1,176 @@ +"use strict"; +/*! + * content-type + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.format = format; +exports.parse = parse; +const TEXT_REGEXP = /^[\u0009\u0020-\u007e\u0080-\u00ff]*$/; +const TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; +/** + * RegExp to match chars that must be quoted-pair in RFC 9110 sec 5.6.4 + */ +const QUOTE_REGEXP = /[\\"]/g; +/** + * RegExp to match type in RFC 9110 sec 8.3.1 + * + * media-type = type "/" subtype + * type = token + * subtype = token + */ +const TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; +/** + * Null object perf optimization. Faster than `Object.create(null)` and `{ __proto__: null }`. + */ +const NullObject = /* @__PURE__ */ (() => { + const C = function () { }; + C.prototype = Object.create(null); + return C; +})(); +/** + * Format an object into a `Content-Type` header. + */ +function format(obj) { + const { type, parameters } = obj; + if (!type || !TYPE_REGEXP.test(type)) { + throw new TypeError(`Invalid type: ${type}`); + } + let result = type; + if (parameters) { + for (const param of Object.keys(parameters)) { + if (!TOKEN_REGEXP.test(param)) { + throw new TypeError(`Invalid parameter name: ${param}`); + } + result += `; ${param}=${qstring(parameters[param])}`; + } + } + return result; +} +/** + * Parse a `Content-Type` header. + */ +function parse(header, options) { + const stopChar = options?.comma === true ? COMMA : 65536; // Sentinel for "no stop char". + const len = header.length; + let index = skipOWS(header, options?.start ?? 0, len); + const valueStart = index; + index = skipValue(header, index, len, stopChar); + const valueEnd = trailingOWS(header, valueStart, index); + const type = header.slice(valueStart, valueEnd).toLowerCase(); + if (options?.parameters === false) { + return { type, index, parameters: new NullObject() }; + } + return parseParameters(header, type, index, len, stopChar); +} +const SP = 32; // " " +const HTAB = 9; // "\t" +const SEMI = 59; // ";" +const EQ = 61; // "=" +const DQUOTE = 34; // '"' +const BSLASH = 92; // "\\" +const COMMA = 44; // "," +/** + * Parses the parameters of a `Content-Type` header starting at the given index. + */ +function parseParameters(header, type, index, len, stopChar) { + const parameters = new NullObject(); + parameter: while (index < len) { + if (header.charCodeAt(index) === stopChar) + break; + index = skipOWS(header, index + 1 /* Skip over ; */, len); + const keyStart = index; + while (index < len) { + const code = header.charCodeAt(index); + if (code === stopChar) + break parameter; + if (code === SEMI) + continue parameter; + if (code === EQ) { + const keyEnd = trailingOWS(header, keyStart, index); + const key = header.slice(keyStart, keyEnd).toLowerCase(); + index = skipOWS(header, index + 1, len); + if (index < len && header.charCodeAt(index) === DQUOTE) { + index++; + let value = ""; + while (index < len) { + const code = header.charCodeAt(index++); + if (code === DQUOTE) { + index = skipValue(header, index, len, stopChar); + if (parameters[key] === undefined) + parameters[key] = value; + break; + } + if (code === BSLASH && index < len) { + value += header[index++]; + continue; + } + value += String.fromCharCode(code); + } + continue parameter; + } + const valueStart = index; + index = skipValue(header, index, len, stopChar); + if (parameters[key] === undefined) { + const valueEnd = trailingOWS(header, valueStart, index); + parameters[key] = header.slice(valueStart, valueEnd); + } + continue parameter; + } + index++; + } + } + return { type, index, parameters }; +} +/** + * Skip over characters until a semicolon or other exit character. + */ +function skipValue(str, index, len, stopChar) { + while (index < len) { + const code = str.charCodeAt(index); + if (code === SEMI || code === stopChar) + break; + index++; + } + return index; +} +/** + * Skip optional whitespace (OWS) in an HTTP header value. + * + * OWS is defined in RFC 9110 sec 5.6.3 as SP (" ") or HTAB ("\t"). + */ +function skipOWS(header, index, len) { + while (index < len) { + const char = header.charCodeAt(index); + if (char !== SP && char !== HTAB) + break; + index++; + } + return index; +} +/** + * Trim optional whitespace (OWS) from the end of a substring. + * + * OWS is defined in RFC 9110 sec 5.6.3 as SP (" ") or HTAB ("\t"). + */ +function trailingOWS(header, start, end) { + while (end > start) { + const char = header.charCodeAt(end - 1); + if (char !== SP && char !== HTAB) + break; + end--; + } + return end; +} +/** + * Serialize a parameter value. + */ +function qstring(str) { + if (TOKEN_REGEXP.test(str)) + return str; + if (TEXT_REGEXP.test(str)) + return `"${str.replace(QUOTE_REGEXP, "\\$&")}"`; + throw new TypeError(`Invalid parameter value: ${str}`); +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/body-parser/node_modules/content-type/dist/index.js.map b/node_modules/body-parser/node_modules/content-type/dist/index.js.map new file mode 100644 index 0000000..2f89192 --- /dev/null +++ b/node_modules/body-parser/node_modules/content-type/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAyCH,wBAoBC;AA+BD,sBAeC;AAzGD,MAAM,WAAW,GAAG,uCAAuC,CAAC;AAC5D,MAAM,YAAY,GAAG,+BAA+B,CAAC;AAErD;;GAEG;AACH,MAAM,YAAY,GAAG,QAAQ,CAAC;AAE9B;;;;;;GAMG;AACH,MAAM,WAAW,GACf,4DAA4D,CAAC;AAE/D;;GAEG;AACH,MAAM,UAAU,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE;IACvC,MAAM,CAAC,GAAG,cAAa,CAAC,CAAC;IACzB,CAAC,CAAC,SAAS,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAClC,OAAO,CAAC,CAAC;AACX,CAAC,CAAC,EAAgC,CAAC;AAWnC;;GAEG;AACH,SAAgB,MAAM,CAAC,GAAyB;IAC9C,MAAM,EAAE,IAAI,EAAE,UAAU,EAAE,GAAG,GAAG,CAAC;IAEjC,IAAI,CAAC,IAAI,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QACrC,MAAM,IAAI,SAAS,CAAC,iBAAiB,IAAI,EAAE,CAAC,CAAC;IAC/C,CAAC;IAED,IAAI,MAAM,GAAG,IAAI,CAAC;IAElB,IAAI,UAAU,EAAE,CAAC;QACf,KAAK,MAAM,KAAK,IAAI,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC;YAC5C,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;gBAC9B,MAAM,IAAI,SAAS,CAAC,2BAA2B,KAAK,EAAE,CAAC,CAAC;YAC1D,CAAC;YAED,MAAM,IAAI,KAAK,KAAK,IAAI,OAAO,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC;QACvD,CAAC;IACH,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC;AA4BD;;GAEG;AACH,SAAgB,KAAK,CAAC,MAAc,EAAE,OAAsB;IAC1D,MAAM,QAAQ,GAAG,OAAO,EAAE,KAAK,KAAK,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAM,CAAC,CAAC,+BAA+B;IAC1F,MAAM,GAAG,GAAG,MAAM,CAAC,MAAM,CAAC;IAC1B,IAAI,KAAK,GAAG,OAAO,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,IAAI,CAAC,EAAE,GAAG,CAAC,CAAC;IAEtD,MAAM,UAAU,GAAG,KAAK,CAAC;IACzB,KAAK,GAAG,SAAS,CAAC,MAAM,EAAE,KAAK,EAAE,GAAG,EAAE,QAAQ,CAAC,CAAC;IAChD,MAAM,QAAQ,GAAG,WAAW,CAAC,MAAM,EAAE,UAAU,EAAE,KAAK,CAAC,CAAC;IACxD,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC,WAAW,EAAE,CAAC;IAE9D,IAAI,OAAO,EAAE,UAAU,KAAK,KAAK,EAAE,CAAC;QAClC,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,UAAU,EAAE,IAAI,UAAU,EAAE,EAAE,CAAC;IACvD,CAAC;IAED,OAAO,eAAe,CAAC,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,QAAQ,CAAC,CAAC;AAC7D,CAAC;AAED,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC,MAAM;AACrB,MAAM,IAAI,GAAG,CAAC,CAAC,CAAC,OAAO;AACvB,MAAM,IAAI,GAAG,EAAE,CAAC,CAAC,MAAM;AACvB,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC,MAAM;AACrB,MAAM,MAAM,GAAG,EAAE,CAAC,CAAC,MAAM;AACzB,MAAM,MAAM,GAAG,EAAE,CAAC,CAAC,OAAO;AAC1B,MAAM,KAAK,GAAG,EAAE,CAAC,CAAC,MAAM;AAExB;;GAEG;AACH,SAAS,eAAe,CACtB,MAAc,EACd,IAAY,EACZ,KAAa,EACb,GAAW,EACX,QAAgB;IAEhB,MAAM,UAAU,GAA2B,IAAI,UAAU,EAAE,CAAC;IAE5D,SAAS,EAAE,OAAO,KAAK,GAAG,GAAG,EAAE,CAAC;QAC9B,IAAI,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,KAAK,QAAQ;YAAE,MAAM;QAEjD,KAAK,GAAG,OAAO,CAAC,MAAM,EAAE,KAAK,GAAG,CAAC,CAAC,iBAAiB,EAAE,GAAG,CAAC,CAAC;QAE1D,MAAM,QAAQ,GAAG,KAAK,CAAC;QAEvB,OAAO,KAAK,GAAG,GAAG,EAAE,CAAC;YACnB,MAAM,IAAI,GAAG,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;YACtC,IAAI,IAAI,KAAK,QAAQ;gBAAE,MAAM,SAAS,CAAC;YAEvC,IAAI,IAAI,KAAK,IAAI;gBAAE,SAAS,SAAS,CAAC;YAEtC,IAAI,IAAI,KAAK,EAAE,EAAE,CAAC;gBAChB,MAAM,MAAM,GAAG,WAAW,CAAC,MAAM,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC;gBACpD,MAAM,GAAG,GAAG,MAAM,CAAC,KAAK,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC,WAAW,EAAE,CAAC;gBAEzD,KAAK,GAAG,OAAO,CAAC,MAAM,EAAE,KAAK,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC;gBAExC,IAAI,KAAK,GAAG,GAAG,IAAI,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,KAAK,MAAM,EAAE,CAAC;oBACvD,KAAK,EAAE,CAAC;oBAER,IAAI,KAAK,GAAG,EAAE,CAAC;oBACf,OAAO,KAAK,GAAG,GAAG,EAAE,CAAC;wBACnB,MAAM,IAAI,GAAG,MAAM,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC,CAAC;wBACxC,IAAI,IAAI,KAAK,MAAM,EAAE,CAAC;4BACpB,KAAK,GAAG,SAAS,CAAC,MAAM,EAAE,KAAK,EAAE,GAAG,EAAE,QAAQ,CAAC,CAAC;4BAChD,IAAI,UAAU,CAAC,GAAG,CAAC,KAAK,SAAS;gCAAE,UAAU,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;4BAC3D,MAAM;wBACR,CAAC;wBAED,IAAI,IAAI,KAAK,MAAM,IAAI,KAAK,GAAG,GAAG,EAAE,CAAC;4BACnC,KAAK,IAAI,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC;4BACzB,SAAS;wBACX,CAAC;wBAED,KAAK,IAAI,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;oBACrC,CAAC;oBAED,SAAS,SAAS,CAAC;gBACrB,CAAC;gBAED,MAAM,UAAU,GAAG,KAAK,CAAC;gBACzB,KAAK,GAAG,SAAS,CAAC,MAAM,EAAE,KAAK,EAAE,GAAG,EAAE,QAAQ,CAAC,CAAC;gBAEhD,IAAI,UAAU,CAAC,GAAG,CAAC,KAAK,SAAS,EAAE,CAAC;oBAClC,MAAM,QAAQ,GAAG,WAAW,CAAC,MAAM,EAAE,UAAU,EAAE,KAAK,CAAC,CAAC;oBACxD,UAAU,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,KAAK,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;gBACvD,CAAC;gBAED,SAAS,SAAS,CAAC;YACrB,CAAC;YAED,KAAK,EAAE,CAAC;QACV,CAAC;IACH,CAAC;IAED,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,UAAU,EAAE,CAAC;AACrC,CAAC;AAED;;GAEG;AACH,SAAS,SAAS,CAChB,GAAW,EACX,KAAa,EACb,GAAW,EACX,QAAgB;IAEhB,OAAO,KAAK,GAAG,GAAG,EAAE,CAAC;QACnB,MAAM,IAAI,GAAG,GAAG,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;QACnC,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,QAAQ;YAAE,MAAM;QAC9C,KAAK,EAAE,CAAC;IACV,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;;;GAIG;AACH,SAAS,OAAO,CAAC,MAAc,EAAE,KAAa,EAAE,GAAW;IACzD,OAAO,KAAK,GAAG,GAAG,EAAE,CAAC;QACnB,MAAM,IAAI,GAAG,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;QACtC,IAAI,IAAI,KAAK,EAAE,IAAI,IAAI,KAAK,IAAI;YAAE,MAAM;QACxC,KAAK,EAAE,CAAC;IACV,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;;;GAIG;AACH,SAAS,WAAW,CAAC,MAAc,EAAE,KAAa,EAAE,GAAW;IAC7D,OAAO,GAAG,GAAG,KAAK,EAAE,CAAC;QACnB,MAAM,IAAI,GAAG,MAAM,CAAC,UAAU,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC;QACxC,IAAI,IAAI,KAAK,EAAE,IAAI,IAAI,KAAK,IAAI;YAAE,MAAM;QACxC,GAAG,EAAE,CAAC;IACR,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAED;;GAEG;AACH,SAAS,OAAO,CAAC,GAAW;IAC1B,IAAI,YAAY,CAAC,IAAI,CAAC,GAAG,CAAC;QAAE,OAAO,GAAG,CAAC;IACvC,IAAI,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC;QAAE,OAAO,IAAI,GAAG,CAAC,OAAO,CAAC,YAAY,EAAE,MAAM,CAAC,GAAG,CAAC;IAE3E,MAAM,IAAI,SAAS,CAAC,4BAA4B,GAAG,EAAE,CAAC,CAAC;AACzD,CAAC","sourcesContent":["/*!\n * content-type\n * Copyright(c) 2015 Douglas Christopher Wilson\n * MIT Licensed\n */\n\nconst TEXT_REGEXP = /^[\\u0009\\u0020-\\u007e\\u0080-\\u00ff]*$/;\nconst TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\n\n/**\n * RegExp to match chars that must be quoted-pair in RFC 9110 sec 5.6.4\n */\nconst QUOTE_REGEXP = /[\\\\\"]/g;\n\n/**\n * RegExp to match type in RFC 9110 sec 8.3.1\n *\n * media-type = type \"/\" subtype\n * type = token\n * subtype = token\n */\nconst TYPE_REGEXP =\n /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\n\n/**\n * Null object perf optimization. Faster than `Object.create(null)` and `{ __proto__: null }`.\n */\nconst NullObject = /* @__PURE__ */ (() => {\n const C = function () {};\n C.prototype = Object.create(null);\n return C;\n})() as unknown as { new (): any };\n\n/**\n * The content type object contains a type string and optional parameters.\n */\nexport interface ContentType {\n type: string;\n index: number;\n parameters: Record;\n}\n\n/**\n * Format an object into a `Content-Type` header.\n */\nexport function format(obj: Partial): string {\n const { type, parameters } = obj;\n\n if (!type || !TYPE_REGEXP.test(type)) {\n throw new TypeError(`Invalid type: ${type}`);\n }\n\n let result = type;\n\n if (parameters) {\n for (const param of Object.keys(parameters)) {\n if (!TOKEN_REGEXP.test(param)) {\n throw new TypeError(`Invalid parameter name: ${param}`);\n }\n\n result += `; ${param}=${qstring(parameters[param])}`;\n }\n }\n\n return result;\n}\n\n/**\n * Options for parsing a `Content-Type` header.\n */\nexport interface ParseOptions {\n /**\n * Exit early on the first semicolon, returning only the type.\n * This is useful for parsing the MIME from `Content-Type` headers.\n *\n * @default false\n */\n parameters?: boolean;\n /**\n * Exits early on a comma, returning the first value and parameters.\n * This is useful for parsing `Accept` headers.\n *\n * @default false\n */\n comma?: boolean;\n /**\n * The index to start parsing from.\n *\n * @default 0\n */\n start?: number;\n}\n\n/**\n * Parse a `Content-Type` header.\n */\nexport function parse(header: string, options?: ParseOptions): ContentType {\n const stopChar = options?.comma === true ? COMMA : 65_536; // Sentinel for \"no stop char\".\n const len = header.length;\n let index = skipOWS(header, options?.start ?? 0, len);\n\n const valueStart = index;\n index = skipValue(header, index, len, stopChar);\n const valueEnd = trailingOWS(header, valueStart, index);\n const type = header.slice(valueStart, valueEnd).toLowerCase();\n\n if (options?.parameters === false) {\n return { type, index, parameters: new NullObject() };\n }\n\n return parseParameters(header, type, index, len, stopChar);\n}\n\nconst SP = 32; // \" \"\nconst HTAB = 9; // \"\\t\"\nconst SEMI = 59; // \";\"\nconst EQ = 61; // \"=\"\nconst DQUOTE = 34; // '\"'\nconst BSLASH = 92; // \"\\\\\"\nconst COMMA = 44; // \",\"\n\n/**\n * Parses the parameters of a `Content-Type` header starting at the given index.\n */\nfunction parseParameters(\n header: string,\n type: string,\n index: number,\n len: number,\n stopChar: number,\n): ContentType {\n const parameters: Record = new NullObject();\n\n parameter: while (index < len) {\n if (header.charCodeAt(index) === stopChar) break;\n\n index = skipOWS(header, index + 1 /* Skip over ; */, len);\n\n const keyStart = index;\n\n while (index < len) {\n const code = header.charCodeAt(index);\n if (code === stopChar) break parameter;\n\n if (code === SEMI) continue parameter;\n\n if (code === EQ) {\n const keyEnd = trailingOWS(header, keyStart, index);\n const key = header.slice(keyStart, keyEnd).toLowerCase();\n\n index = skipOWS(header, index + 1, len);\n\n if (index < len && header.charCodeAt(index) === DQUOTE) {\n index++;\n\n let value = \"\";\n while (index < len) {\n const code = header.charCodeAt(index++);\n if (code === DQUOTE) {\n index = skipValue(header, index, len, stopChar);\n if (parameters[key] === undefined) parameters[key] = value;\n break;\n }\n\n if (code === BSLASH && index < len) {\n value += header[index++];\n continue;\n }\n\n value += String.fromCharCode(code);\n }\n\n continue parameter;\n }\n\n const valueStart = index;\n index = skipValue(header, index, len, stopChar);\n\n if (parameters[key] === undefined) {\n const valueEnd = trailingOWS(header, valueStart, index);\n parameters[key] = header.slice(valueStart, valueEnd);\n }\n\n continue parameter;\n }\n\n index++;\n }\n }\n\n return { type, index, parameters };\n}\n\n/**\n * Skip over characters until a semicolon or other exit character.\n */\nfunction skipValue(\n str: string,\n index: number,\n len: number,\n stopChar: number,\n): number {\n while (index < len) {\n const code = str.charCodeAt(index);\n if (code === SEMI || code === stopChar) break;\n index++;\n }\n return index;\n}\n\n/**\n * Skip optional whitespace (OWS) in an HTTP header value.\n *\n * OWS is defined in RFC 9110 sec 5.6.3 as SP (\" \") or HTAB (\"\\t\").\n */\nfunction skipOWS(header: string, index: number, len: number): number {\n while (index < len) {\n const char = header.charCodeAt(index);\n if (char !== SP && char !== HTAB) break;\n index++;\n }\n return index;\n}\n\n/**\n * Trim optional whitespace (OWS) from the end of a substring.\n *\n * OWS is defined in RFC 9110 sec 5.6.3 as SP (\" \") or HTAB (\"\\t\").\n */\nfunction trailingOWS(header: string, start: number, end: number): number {\n while (end > start) {\n const char = header.charCodeAt(end - 1);\n if (char !== SP && char !== HTAB) break;\n end--;\n }\n return end;\n}\n\n/**\n * Serialize a parameter value.\n */\nfunction qstring(str: string): string {\n if (TOKEN_REGEXP.test(str)) return str;\n if (TEXT_REGEXP.test(str)) return `\"${str.replace(QUOTE_REGEXP, \"\\\\$&\")}\"`;\n\n throw new TypeError(`Invalid parameter value: ${str}`);\n}\n"]} \ No newline at end of file diff --git a/node_modules/body-parser/node_modules/content-type/package.json b/node_modules/body-parser/node_modules/content-type/package.json new file mode 100644 index 0000000..4a403eb --- /dev/null +++ b/node_modules/body-parser/node_modules/content-type/package.json @@ -0,0 +1,52 @@ +{ + "name": "content-type", + "version": "2.1.0", + "description": "Create and parse HTTP Content-Type header", + "keywords": [ + "content-type", + "http", + "req", + "res", + "rfc7231", + "rfc9110" + ], + "repository": "jshttp/content-type", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + }, + "license": "MIT", + "author": "Douglas Christopher Wilson ", + "type": "commonjs", + "exports": "./dist/index.js", + "main": "./dist/index.js", + "typings": "./dist/index.d.ts", + "files": [ + "dist/" + ], + "scripts": { + "bench": "vitest bench", + "build": "ts-scripts build", + "format": "ts-scripts format", + "prepare": "ts-scripts install && npm run build", + "specs": "ts-scripts specs", + "test": "ts-scripts test" + }, + "devDependencies": { + "@borderless/ts-scripts": "^0.15.0", + "@vitest/coverage-v8": "^3.0.5", + "typescript": "^5.7.3", + "vitest": "^3.2.4" + }, + "engines": { + "node": ">=18" + }, + "ts-scripts": { + "dist": [ + "dist" + ], + "project": [ + "tsconfig.build.json" + ] + } +} diff --git a/node_modules/body-parser/package.json b/node_modules/body-parser/package.json new file mode 100644 index 0000000..842cfbd --- /dev/null +++ b/node_modules/body-parser/package.json @@ -0,0 +1,65 @@ +{ + "name": "body-parser", + "description": "Node.js body parsing middleware", + "version": "2.3.0", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "repository": "expressjs/body-parser", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + }, + "type": "commonjs", + "exports": { + ".": "./index.js", + "./package.json": "./package.json", + "./json": "./lib/types/json.js", + "./raw": "./lib/types/raw.js", + "./text": "./lib/types/text.js", + "./urlencoded": "./lib/types/urlencoded.js", + "./lib/*": "./lib/*.js", + "./lib/*.js": "./lib/*.js", + "./lib/types/*": "./lib/types/*.js", + "./lib/types/*.js": "./lib/types/*.js" + }, + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^2.0.0", + "debug": "^4.4.3", + "http-errors": "^2.0.1", + "iconv-lite": "^0.7.2", + "on-finished": "^2.4.1", + "qs": "^6.15.2", + "raw-body": "^3.0.2", + "type-is": "^2.1.0" + }, + "devDependencies": { + "eslint": "^8.57.1", + "eslint-config-standard": "^14.1.1", + "eslint-plugin-import": "^2.32.0", + "eslint-plugin-markdown": "^3.0.1", + "eslint-plugin-node": "^11.1.0", + "eslint-plugin-promise": "^6.6.0", + "eslint-plugin-standard": "^4.1.0", + "mocha": "^11.7.6", + "nyc": "^17.1.0", + "supertest": "^7.2.2" + }, + "files": [ + "lib/", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">=18" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --check-leaks test/", + "test-ci": "nyc --reporter=lcovonly --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/node_modules/buffer-from/LICENSE b/node_modules/buffer-from/LICENSE new file mode 100644 index 0000000..e4bf1d6 --- /dev/null +++ b/node_modules/buffer-from/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016, 2018 Linus Unnebäck + +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. diff --git a/node_modules/buffer-from/index.js b/node_modules/buffer-from/index.js new file mode 100644 index 0000000..e1a58b5 --- /dev/null +++ b/node_modules/buffer-from/index.js @@ -0,0 +1,72 @@ +/* eslint-disable node/no-deprecated-api */ + +var toString = Object.prototype.toString + +var isModern = ( + typeof Buffer !== 'undefined' && + typeof Buffer.alloc === 'function' && + typeof Buffer.allocUnsafe === 'function' && + typeof Buffer.from === 'function' +) + +function isArrayBuffer (input) { + return toString.call(input).slice(8, -1) === 'ArrayBuffer' +} + +function fromArrayBuffer (obj, byteOffset, length) { + byteOffset >>>= 0 + + var maxLength = obj.byteLength - byteOffset + + if (maxLength < 0) { + throw new RangeError("'offset' is out of bounds") + } + + if (length === undefined) { + length = maxLength + } else { + length >>>= 0 + + if (length > maxLength) { + throw new RangeError("'length' is out of bounds") + } + } + + return isModern + ? Buffer.from(obj.slice(byteOffset, byteOffset + length)) + : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length))) +} + +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + return isModern + ? Buffer.from(string, encoding) + : new Buffer(string, encoding) +} + +function bufferFrom (value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (isArrayBuffer(value)) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } + + return isModern + ? Buffer.from(value) + : new Buffer(value) +} + +module.exports = bufferFrom diff --git a/node_modules/buffer-from/package.json b/node_modules/buffer-from/package.json new file mode 100644 index 0000000..6ac5327 --- /dev/null +++ b/node_modules/buffer-from/package.json @@ -0,0 +1,19 @@ +{ + "name": "buffer-from", + "version": "1.1.2", + "license": "MIT", + "repository": "LinusU/buffer-from", + "files": [ + "index.js" + ], + "scripts": { + "test": "standard && node test" + }, + "devDependencies": { + "standard": "^12.0.1" + }, + "keywords": [ + "buffer", + "buffer from" + ] +} diff --git a/node_modules/buffer-from/readme.md b/node_modules/buffer-from/readme.md new file mode 100644 index 0000000..9880a55 --- /dev/null +++ b/node_modules/buffer-from/readme.md @@ -0,0 +1,69 @@ +# Buffer From + +A [ponyfill](https://ponyfill.com) for `Buffer.from`, uses native implementation if available. + +## Installation + +```sh +npm install --save buffer-from +``` + +## Usage + +```js +const bufferFrom = require('buffer-from') + +console.log(bufferFrom([1, 2, 3, 4])) +//=> + +const arr = new Uint8Array([1, 2, 3, 4]) +console.log(bufferFrom(arr.buffer, 1, 2)) +//=> + +console.log(bufferFrom('test', 'utf8')) +//=> + +const buf = bufferFrom('test') +console.log(bufferFrom(buf)) +//=> +``` + +## API + +### bufferFrom(array) + +- `array` <Array> + +Allocates a new `Buffer` using an `array` of octets. + +### bufferFrom(arrayBuffer[, byteOffset[, length]]) + +- `arrayBuffer` <ArrayBuffer> The `.buffer` property of a TypedArray or ArrayBuffer +- `byteOffset` <Integer> Where to start copying from `arrayBuffer`. **Default:** `0` +- `length` <Integer> How many bytes to copy from `arrayBuffer`. **Default:** `arrayBuffer.length - byteOffset` + +When passed a reference to the `.buffer` property of a TypedArray instance, the +newly created `Buffer` will share the same allocated memory as the TypedArray. + +The optional `byteOffset` and `length` arguments specify a memory range within +the `arrayBuffer` that will be shared by the `Buffer`. + +### bufferFrom(buffer) + +- `buffer` <Buffer> An existing `Buffer` to copy data from + +Copies the passed `buffer` data onto a new `Buffer` instance. + +### bufferFrom(string[, encoding]) + +- `string` <String> A string to encode. +- `encoding` <String> The encoding of `string`. **Default:** `'utf8'` + +Creates a new `Buffer` containing the given JavaScript string `string`. If +provided, the `encoding` parameter identifies the character encoding of +`string`. + +## See also + +- [buffer-alloc](https://github.com/LinusU/buffer-alloc) A ponyfill for `Buffer.alloc` +- [buffer-alloc-unsafe](https://github.com/LinusU/buffer-alloc-unsafe) A ponyfill for `Buffer.allocUnsafe` diff --git a/node_modules/busboy/.eslintrc.js b/node_modules/busboy/.eslintrc.js new file mode 100644 index 0000000..be9311d --- /dev/null +++ b/node_modules/busboy/.eslintrc.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = { + extends: '@mscdex/eslint-config', +}; diff --git a/node_modules/busboy/.github/workflows/ci.yml b/node_modules/busboy/.github/workflows/ci.yml new file mode 100644 index 0000000..799bae0 --- /dev/null +++ b/node_modules/busboy/.github/workflows/ci.yml @@ -0,0 +1,24 @@ +name: CI + +on: + pull_request: + push: + branches: [ master ] + +jobs: + tests-linux: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + node-version: [10.16.0, 10.x, 12.x, 14.x, 16.x] + steps: + - uses: actions/checkout@v2 + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v1 + with: + node-version: ${{ matrix.node-version }} + - name: Install module + run: npm install + - name: Run tests + run: npm test diff --git a/node_modules/busboy/.github/workflows/lint.yml b/node_modules/busboy/.github/workflows/lint.yml new file mode 100644 index 0000000..9f9e1f5 --- /dev/null +++ b/node_modules/busboy/.github/workflows/lint.yml @@ -0,0 +1,23 @@ +name: lint + +on: + pull_request: + push: + branches: [ master ] + +env: + NODE_VERSION: 16.x + +jobs: + lint-js: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Use Node.js ${{ env.NODE_VERSION }} + uses: actions/setup-node@v1 + with: + node-version: ${{ env.NODE_VERSION }} + - name: Install ESLint + ESLint configs/plugins + run: npm install --only=dev + - name: Lint files + run: npm run lint diff --git a/node_modules/busboy/LICENSE b/node_modules/busboy/LICENSE new file mode 100644 index 0000000..290762e --- /dev/null +++ b/node_modules/busboy/LICENSE @@ -0,0 +1,19 @@ +Copyright Brian White. All rights reserved. + +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. \ No newline at end of file diff --git a/node_modules/busboy/README.md b/node_modules/busboy/README.md new file mode 100644 index 0000000..654af30 --- /dev/null +++ b/node_modules/busboy/README.md @@ -0,0 +1,191 @@ +# Description + +A node.js module for parsing incoming HTML form data. + +Changes (breaking or otherwise) in v1.0.0 can be found [here](https://github.com/mscdex/busboy/issues/266). + +# Requirements + +* [node.js](http://nodejs.org/) -- v10.16.0 or newer + + +# Install + + npm install busboy + + +# Examples + +* Parsing (multipart) with default options: + +```js +const http = require('http'); + +const busboy = require('busboy'); + +http.createServer((req, res) => { + if (req.method === 'POST') { + console.log('POST request'); + const bb = busboy({ headers: req.headers }); + bb.on('file', (name, file, info) => { + const { filename, encoding, mimeType } = info; + console.log( + `File [${name}]: filename: %j, encoding: %j, mimeType: %j`, + filename, + encoding, + mimeType + ); + file.on('data', (data) => { + console.log(`File [${name}] got ${data.length} bytes`); + }).on('close', () => { + console.log(`File [${name}] done`); + }); + }); + bb.on('field', (name, val, info) => { + console.log(`Field [${name}]: value: %j`, val); + }); + bb.on('close', () => { + console.log('Done parsing form!'); + res.writeHead(303, { Connection: 'close', Location: '/' }); + res.end(); + }); + req.pipe(bb); + } else if (req.method === 'GET') { + res.writeHead(200, { Connection: 'close' }); + res.end(` + + + +
+
+
+ +
+ + + `); + } +}).listen(8000, () => { + console.log('Listening for requests'); +}); + +// Example output: +// +// Listening for requests +// < ... form submitted ... > +// POST request +// File [filefield]: filename: "logo.jpg", encoding: "binary", mime: "image/jpeg" +// File [filefield] got 11912 bytes +// Field [textfield]: value: "testing! :-)" +// File [filefield] done +// Done parsing form! +``` + +* Save all incoming files to disk: + +```js +const { randomFillSync } = require('crypto'); +const fs = require('fs'); +const http = require('http'); +const os = require('os'); +const path = require('path'); + +const busboy = require('busboy'); + +const random = (() => { + const buf = Buffer.alloc(16); + return () => randomFillSync(buf).toString('hex'); +})(); + +http.createServer((req, res) => { + if (req.method === 'POST') { + const bb = busboy({ headers: req.headers }); + bb.on('file', (name, file, info) => { + const saveTo = path.join(os.tmpdir(), `busboy-upload-${random()}`); + file.pipe(fs.createWriteStream(saveTo)); + }); + bb.on('close', () => { + res.writeHead(200, { 'Connection': 'close' }); + res.end(`That's all folks!`); + }); + req.pipe(bb); + return; + } + res.writeHead(404); + res.end(); +}).listen(8000, () => { + console.log('Listening for requests'); +}); +``` + + +# API + +## Exports + +`busboy` exports a single function: + +**( _function_ )**(< _object_ >config) - Creates and returns a new _Writable_ form parser stream. + +* Valid `config` properties: + + * **headers** - _object_ - These are the HTTP headers of the incoming request, which are used by individual parsers. + + * **highWaterMark** - _integer_ - highWaterMark to use for the parser stream. **Default:** node's _stream.Writable_ default. + + * **fileHwm** - _integer_ - highWaterMark to use for individual file streams. **Default:** node's _stream.Readable_ default. + + * **defCharset** - _string_ - Default character set to use when one isn't defined. **Default:** `'utf8'`. + + * **defParamCharset** - _string_ - For multipart forms, the default character set to use for values of part header parameters (e.g. filename) that are not extended parameters (that contain an explicit charset). **Default:** `'latin1'`. + + * **preservePath** - _boolean_ - If paths in filenames from file parts in a `'multipart/form-data'` request shall be preserved. **Default:** `false`. + + * **limits** - _object_ - Various limits on incoming data. Valid properties are: + + * **fieldNameSize** - _integer_ - Max field name size (in bytes). **Default:** `100`. + + * **fieldSize** - _integer_ - Max field value size (in bytes). **Default:** `1048576` (1MB). + + * **fields** - _integer_ - Max number of non-file fields. **Default:** `Infinity`. + + * **fileSize** - _integer_ - For multipart forms, the max file size (in bytes). **Default:** `Infinity`. + + * **files** - _integer_ - For multipart forms, the max number of file fields. **Default:** `Infinity`. + + * **parts** - _integer_ - For multipart forms, the max number of parts (fields + files). **Default:** `Infinity`. + + * **headerPairs** - _integer_ - For multipart forms, the max number of header key-value pairs to parse. **Default:** `2000` (same as node's http module). + +This function can throw exceptions if there is something wrong with the values in `config`. For example, if the Content-Type in `headers` is missing entirely, is not a supported type, or is missing the boundary for `'multipart/form-data'` requests. + +## (Special) Parser stream events + +* **file**(< _string_ >name, < _Readable_ >stream, < _object_ >info) - Emitted for each new file found. `name` contains the form field name. `stream` is a _Readable_ stream containing the file's data. No transformations/conversions (e.g. base64 to raw binary) are done on the file's data. `info` contains the following properties: + + * `filename` - _string_ - If supplied, this contains the file's filename. **WARNING:** You should almost _never_ use this value as-is (especially if you are using `preservePath: true` in your `config`) as it could contain malicious input. You are better off generating your own (safe) filenames, or at the very least using a hash of the filename. + + * `encoding` - _string_ - The file's `'Content-Transfer-Encoding'` value. + + * `mimeType` - _string_ - The file's `'Content-Type'` value. + + **Note:** If you listen for this event, you should always consume the `stream` whether you care about its contents or not (you can simply do `stream.resume();` if you want to discard/skip the contents), otherwise the `'finish'`/`'close'` event will never fire on the busboy parser stream. + However, if you aren't accepting files, you can either simply not listen for the `'file'` event at all or set `limits.files` to `0`, and any/all files will be automatically skipped (these skipped files will still count towards any configured `limits.files` and `limits.parts` limits though). + + **Note:** If a configured `limits.fileSize` limit was reached for a file, `stream` will both have a boolean property `truncated` set to `true` (best checked at the end of the stream) and emit a `'limit'` event to notify you when this happens. + +* **field**(< _string_ >name, < _string_ >value, < _object_ >info) - Emitted for each new non-file field found. `name` contains the form field name. `value` contains the string value of the field. `info` contains the following properties: + + * `nameTruncated` - _boolean_ - Whether `name` was truncated or not (due to a configured `limits.fieldNameSize` limit) + + * `valueTruncated` - _boolean_ - Whether `value` was truncated or not (due to a configured `limits.fieldSize` limit) + + * `encoding` - _string_ - The field's `'Content-Transfer-Encoding'` value. + + * `mimeType` - _string_ - The field's `'Content-Type'` value. + +* **partsLimit**() - Emitted when the configured `limits.parts` limit has been reached. No more `'file'` or `'field'` events will be emitted. + +* **filesLimit**() - Emitted when the configured `limits.files` limit has been reached. No more `'file'` events will be emitted. + +* **fieldsLimit**() - Emitted when the configured `limits.fields` limit has been reached. No more `'field'` events will be emitted. diff --git a/node_modules/busboy/bench/bench-multipart-fields-100mb-big.js b/node_modules/busboy/bench/bench-multipart-fields-100mb-big.js new file mode 100644 index 0000000..ef15729 --- /dev/null +++ b/node_modules/busboy/bench/bench-multipart-fields-100mb-big.js @@ -0,0 +1,149 @@ +'use strict'; + +function createMultipartBuffers(boundary, sizes) { + const bufs = []; + for (let i = 0; i < sizes.length; ++i) { + const mb = sizes[i] * 1024 * 1024; + bufs.push(Buffer.from([ + `--${boundary}`, + `content-disposition: form-data; name="field${i + 1}"`, + '', + '0'.repeat(mb), + '', + ].join('\r\n'))); + } + bufs.push(Buffer.from([ + `--${boundary}--`, + '', + ].join('\r\n'))); + return bufs; +} + +const boundary = '-----------------------------168072824752491622650073'; +const buffers = createMultipartBuffers(boundary, [ + 10, + 10, + 10, + 20, + 50, +]); +const calls = { + partBegin: 0, + headerField: 0, + headerValue: 0, + headerEnd: 0, + headersEnd: 0, + partData: 0, + partEnd: 0, + end: 0, +}; + +const moduleName = process.argv[2]; +switch (moduleName) { + case 'busboy': { + const busboy = require('busboy'); + + const parser = busboy({ + limits: { + fieldSizeLimit: Infinity, + }, + headers: { + 'content-type': `multipart/form-data; boundary=${boundary}`, + }, + }); + parser.on('field', (name, val, info) => { + ++calls.partBegin; + ++calls.partData; + ++calls.partEnd; + }).on('close', () => { + ++calls.end; + console.timeEnd(moduleName); + }); + + console.time(moduleName); + for (const buf of buffers) + parser.write(buf); + break; + } + + case 'formidable': { + const { MultipartParser } = require('formidable'); + + const parser = new MultipartParser(); + parser.initWithBoundary(boundary); + parser.on('data', ({ name }) => { + ++calls[name]; + if (name === 'end') + console.timeEnd(moduleName); + }); + + console.time(moduleName); + for (const buf of buffers) + parser.write(buf); + + break; + } + + case 'multiparty': { + const { Readable } = require('stream'); + + const { Form } = require('multiparty'); + + const form = new Form({ + maxFieldsSize: Infinity, + maxFields: Infinity, + maxFilesSize: Infinity, + autoFields: false, + autoFiles: false, + }); + + const req = new Readable({ read: () => {} }); + req.headers = { + 'content-type': `multipart/form-data; boundary=${boundary}`, + }; + + function hijack(name, fn) { + const oldFn = form[name]; + form[name] = function() { + fn(); + return oldFn.apply(this, arguments); + }; + } + + hijack('onParseHeaderField', () => { + ++calls.headerField; + }); + hijack('onParseHeaderValue', () => { + ++calls.headerValue; + }); + hijack('onParsePartBegin', () => { + ++calls.partBegin; + }); + hijack('onParsePartData', () => { + ++calls.partData; + }); + hijack('onParsePartEnd', () => { + ++calls.partEnd; + }); + + form.on('close', () => { + ++calls.end; + console.timeEnd(moduleName); + }).on('part', (p) => p.resume()); + + console.time(moduleName); + form.parse(req); + for (const buf of buffers) + req.push(buf); + req.push(null); + + break; + } + + default: + if (moduleName === undefined) + console.error('Missing parser module name'); + else + console.error(`Invalid parser module name: ${moduleName}`); + process.exit(1); +} diff --git a/node_modules/busboy/bench/bench-multipart-fields-100mb-small.js b/node_modules/busboy/bench/bench-multipart-fields-100mb-small.js new file mode 100644 index 0000000..f32d421 --- /dev/null +++ b/node_modules/busboy/bench/bench-multipart-fields-100mb-small.js @@ -0,0 +1,143 @@ +'use strict'; + +function createMultipartBuffers(boundary, sizes) { + const bufs = []; + for (let i = 0; i < sizes.length; ++i) { + const mb = sizes[i] * 1024 * 1024; + bufs.push(Buffer.from([ + `--${boundary}`, + `content-disposition: form-data; name="field${i + 1}"`, + '', + '0'.repeat(mb), + '', + ].join('\r\n'))); + } + bufs.push(Buffer.from([ + `--${boundary}--`, + '', + ].join('\r\n'))); + return bufs; +} + +const boundary = '-----------------------------168072824752491622650073'; +const buffers = createMultipartBuffers(boundary, (new Array(100)).fill(1)); +const calls = { + partBegin: 0, + headerField: 0, + headerValue: 0, + headerEnd: 0, + headersEnd: 0, + partData: 0, + partEnd: 0, + end: 0, +}; + +const moduleName = process.argv[2]; +switch (moduleName) { + case 'busboy': { + const busboy = require('busboy'); + + const parser = busboy({ + limits: { + fieldSizeLimit: Infinity, + }, + headers: { + 'content-type': `multipart/form-data; boundary=${boundary}`, + }, + }); + parser.on('field', (name, val, info) => { + ++calls.partBegin; + ++calls.partData; + ++calls.partEnd; + }).on('close', () => { + ++calls.end; + console.timeEnd(moduleName); + }); + + console.time(moduleName); + for (const buf of buffers) + parser.write(buf); + break; + } + + case 'formidable': { + const { MultipartParser } = require('formidable'); + + const parser = new MultipartParser(); + parser.initWithBoundary(boundary); + parser.on('data', ({ name }) => { + ++calls[name]; + if (name === 'end') + console.timeEnd(moduleName); + }); + + console.time(moduleName); + for (const buf of buffers) + parser.write(buf); + + break; + } + + case 'multiparty': { + const { Readable } = require('stream'); + + const { Form } = require('multiparty'); + + const form = new Form({ + maxFieldsSize: Infinity, + maxFields: Infinity, + maxFilesSize: Infinity, + autoFields: false, + autoFiles: false, + }); + + const req = new Readable({ read: () => {} }); + req.headers = { + 'content-type': `multipart/form-data; boundary=${boundary}`, + }; + + function hijack(name, fn) { + const oldFn = form[name]; + form[name] = function() { + fn(); + return oldFn.apply(this, arguments); + }; + } + + hijack('onParseHeaderField', () => { + ++calls.headerField; + }); + hijack('onParseHeaderValue', () => { + ++calls.headerValue; + }); + hijack('onParsePartBegin', () => { + ++calls.partBegin; + }); + hijack('onParsePartData', () => { + ++calls.partData; + }); + hijack('onParsePartEnd', () => { + ++calls.partEnd; + }); + + form.on('close', () => { + ++calls.end; + console.timeEnd(moduleName); + }).on('part', (p) => p.resume()); + + console.time(moduleName); + form.parse(req); + for (const buf of buffers) + req.push(buf); + req.push(null); + + break; + } + + default: + if (moduleName === undefined) + console.error('Missing parser module name'); + else + console.error(`Invalid parser module name: ${moduleName}`); + process.exit(1); +} diff --git a/node_modules/busboy/bench/bench-multipart-files-100mb-big.js b/node_modules/busboy/bench/bench-multipart-files-100mb-big.js new file mode 100644 index 0000000..b46bdee --- /dev/null +++ b/node_modules/busboy/bench/bench-multipart-files-100mb-big.js @@ -0,0 +1,154 @@ +'use strict'; + +function createMultipartBuffers(boundary, sizes) { + const bufs = []; + for (let i = 0; i < sizes.length; ++i) { + const mb = sizes[i] * 1024 * 1024; + bufs.push(Buffer.from([ + `--${boundary}`, + `content-disposition: form-data; name="file${i + 1}"; ` + + `filename="random${i + 1}.bin"`, + 'content-type: application/octet-stream', + '', + '0'.repeat(mb), + '', + ].join('\r\n'))); + } + bufs.push(Buffer.from([ + `--${boundary}--`, + '', + ].join('\r\n'))); + return bufs; +} + +const boundary = '-----------------------------168072824752491622650073'; +const buffers = createMultipartBuffers(boundary, [ + 10, + 10, + 10, + 20, + 50, +]); +const calls = { + partBegin: 0, + headerField: 0, + headerValue: 0, + headerEnd: 0, + headersEnd: 0, + partData: 0, + partEnd: 0, + end: 0, +}; + +const moduleName = process.argv[2]; +switch (moduleName) { + case 'busboy': { + const busboy = require('busboy'); + + const parser = busboy({ + limits: { + fieldSizeLimit: Infinity, + }, + headers: { + 'content-type': `multipart/form-data; boundary=${boundary}`, + }, + }); + parser.on('file', (name, stream, info) => { + ++calls.partBegin; + stream.on('data', (chunk) => { + ++calls.partData; + }).on('end', () => { + ++calls.partEnd; + }); + }).on('close', () => { + ++calls.end; + console.timeEnd(moduleName); + }); + + console.time(moduleName); + for (const buf of buffers) + parser.write(buf); + break; + } + + case 'formidable': { + const { MultipartParser } = require('formidable'); + + const parser = new MultipartParser(); + parser.initWithBoundary(boundary); + parser.on('data', ({ name }) => { + ++calls[name]; + if (name === 'end') + console.timeEnd(moduleName); + }); + + console.time(moduleName); + for (const buf of buffers) + parser.write(buf); + + break; + } + + case 'multiparty': { + const { Readable } = require('stream'); + + const { Form } = require('multiparty'); + + const form = new Form({ + maxFieldsSize: Infinity, + maxFields: Infinity, + maxFilesSize: Infinity, + autoFields: false, + autoFiles: false, + }); + + const req = new Readable({ read: () => {} }); + req.headers = { + 'content-type': `multipart/form-data; boundary=${boundary}`, + }; + + function hijack(name, fn) { + const oldFn = form[name]; + form[name] = function() { + fn(); + return oldFn.apply(this, arguments); + }; + } + + hijack('onParseHeaderField', () => { + ++calls.headerField; + }); + hijack('onParseHeaderValue', () => { + ++calls.headerValue; + }); + hijack('onParsePartBegin', () => { + ++calls.partBegin; + }); + hijack('onParsePartData', () => { + ++calls.partData; + }); + hijack('onParsePartEnd', () => { + ++calls.partEnd; + }); + + form.on('close', () => { + ++calls.end; + console.timeEnd(moduleName); + }).on('part', (p) => p.resume()); + + console.time(moduleName); + form.parse(req); + for (const buf of buffers) + req.push(buf); + req.push(null); + + break; + } + + default: + if (moduleName === undefined) + console.error('Missing parser module name'); + else + console.error(`Invalid parser module name: ${moduleName}`); + process.exit(1); +} diff --git a/node_modules/busboy/bench/bench-multipart-files-100mb-small.js b/node_modules/busboy/bench/bench-multipart-files-100mb-small.js new file mode 100644 index 0000000..46b5dff --- /dev/null +++ b/node_modules/busboy/bench/bench-multipart-files-100mb-small.js @@ -0,0 +1,148 @@ +'use strict'; + +function createMultipartBuffers(boundary, sizes) { + const bufs = []; + for (let i = 0; i < sizes.length; ++i) { + const mb = sizes[i] * 1024 * 1024; + bufs.push(Buffer.from([ + `--${boundary}`, + `content-disposition: form-data; name="file${i + 1}"; ` + + `filename="random${i + 1}.bin"`, + 'content-type: application/octet-stream', + '', + '0'.repeat(mb), + '', + ].join('\r\n'))); + } + bufs.push(Buffer.from([ + `--${boundary}--`, + '', + ].join('\r\n'))); + return bufs; +} + +const boundary = '-----------------------------168072824752491622650073'; +const buffers = createMultipartBuffers(boundary, (new Array(100)).fill(1)); +const calls = { + partBegin: 0, + headerField: 0, + headerValue: 0, + headerEnd: 0, + headersEnd: 0, + partData: 0, + partEnd: 0, + end: 0, +}; + +const moduleName = process.argv[2]; +switch (moduleName) { + case 'busboy': { + const busboy = require('busboy'); + + const parser = busboy({ + limits: { + fieldSizeLimit: Infinity, + }, + headers: { + 'content-type': `multipart/form-data; boundary=${boundary}`, + }, + }); + parser.on('file', (name, stream, info) => { + ++calls.partBegin; + stream.on('data', (chunk) => { + ++calls.partData; + }).on('end', () => { + ++calls.partEnd; + }); + }).on('close', () => { + ++calls.end; + console.timeEnd(moduleName); + }); + + console.time(moduleName); + for (const buf of buffers) + parser.write(buf); + break; + } + + case 'formidable': { + const { MultipartParser } = require('formidable'); + + const parser = new MultipartParser(); + parser.initWithBoundary(boundary); + parser.on('data', ({ name }) => { + ++calls[name]; + if (name === 'end') + console.timeEnd(moduleName); + }); + + console.time(moduleName); + for (const buf of buffers) + parser.write(buf); + + break; + } + + case 'multiparty': { + const { Readable } = require('stream'); + + const { Form } = require('multiparty'); + + const form = new Form({ + maxFieldsSize: Infinity, + maxFields: Infinity, + maxFilesSize: Infinity, + autoFields: false, + autoFiles: false, + }); + + const req = new Readable({ read: () => {} }); + req.headers = { + 'content-type': `multipart/form-data; boundary=${boundary}`, + }; + + function hijack(name, fn) { + const oldFn = form[name]; + form[name] = function() { + fn(); + return oldFn.apply(this, arguments); + }; + } + + hijack('onParseHeaderField', () => { + ++calls.headerField; + }); + hijack('onParseHeaderValue', () => { + ++calls.headerValue; + }); + hijack('onParsePartBegin', () => { + ++calls.partBegin; + }); + hijack('onParsePartData', () => { + ++calls.partData; + }); + hijack('onParsePartEnd', () => { + ++calls.partEnd; + }); + + form.on('close', () => { + ++calls.end; + console.timeEnd(moduleName); + }).on('part', (p) => p.resume()); + + console.time(moduleName); + form.parse(req); + for (const buf of buffers) + req.push(buf); + req.push(null); + + break; + } + + default: + if (moduleName === undefined) + console.error('Missing parser module name'); + else + console.error(`Invalid parser module name: ${moduleName}`); + process.exit(1); +} diff --git a/node_modules/busboy/bench/bench-urlencoded-fields-100pairs-small.js b/node_modules/busboy/bench/bench-urlencoded-fields-100pairs-small.js new file mode 100644 index 0000000..5c337df --- /dev/null +++ b/node_modules/busboy/bench/bench-urlencoded-fields-100pairs-small.js @@ -0,0 +1,101 @@ +'use strict'; + +const buffers = [ + Buffer.from( + (new Array(100)).fill('').map((_, i) => `key${i}=value${i}`).join('&') + ), +]; +const calls = { + field: 0, + end: 0, +}; + +let n = 3e3; + +const moduleName = process.argv[2]; +switch (moduleName) { + case 'busboy': { + const busboy = require('busboy'); + + console.time(moduleName); + (function next() { + const parser = busboy({ + limits: { + fieldSizeLimit: Infinity, + }, + headers: { + 'content-type': 'application/x-www-form-urlencoded; charset=utf-8', + }, + }); + parser.on('field', (name, val, info) => { + ++calls.field; + }).on('close', () => { + ++calls.end; + if (--n === 0) + console.timeEnd(moduleName); + else + process.nextTick(next); + }); + + for (const buf of buffers) + parser.write(buf); + parser.end(); + })(); + break; + } + + case 'formidable': { + const QuerystringParser = + require('formidable/src/parsers/Querystring.js'); + + console.time(moduleName); + (function next() { + const parser = new QuerystringParser(); + parser.on('data', (obj) => { + ++calls.field; + }).on('end', () => { + ++calls.end; + if (--n === 0) + console.timeEnd(moduleName); + else + process.nextTick(next); + }); + + for (const buf of buffers) + parser.write(buf); + parser.end(); + })(); + break; + } + + case 'formidable-streaming': { + const QuerystringParser = + require('formidable/src/parsers/StreamingQuerystring.js'); + + console.time(moduleName); + (function next() { + const parser = new QuerystringParser(); + parser.on('data', (obj) => { + ++calls.field; + }).on('end', () => { + ++calls.end; + if (--n === 0) + console.timeEnd(moduleName); + else + process.nextTick(next); + }); + + for (const buf of buffers) + parser.write(buf); + parser.end(); + })(); + break; + } + + default: + if (moduleName === undefined) + console.error('Missing parser module name'); + else + console.error(`Invalid parser module name: ${moduleName}`); + process.exit(1); +} diff --git a/node_modules/busboy/bench/bench-urlencoded-fields-900pairs-small-alt.js b/node_modules/busboy/bench/bench-urlencoded-fields-900pairs-small-alt.js new file mode 100644 index 0000000..1f5645c --- /dev/null +++ b/node_modules/busboy/bench/bench-urlencoded-fields-900pairs-small-alt.js @@ -0,0 +1,84 @@ +'use strict'; + +const buffers = [ + Buffer.from( + (new Array(900)).fill('').map((_, i) => `key${i}=value${i}`).join('&') + ), +]; +const calls = { + field: 0, + end: 0, +}; + +const moduleName = process.argv[2]; +switch (moduleName) { + case 'busboy': { + const busboy = require('busboy'); + + console.time(moduleName); + const parser = busboy({ + limits: { + fieldSizeLimit: Infinity, + }, + headers: { + 'content-type': 'application/x-www-form-urlencoded; charset=utf-8', + }, + }); + parser.on('field', (name, val, info) => { + ++calls.field; + }).on('close', () => { + ++calls.end; + console.timeEnd(moduleName); + }); + + for (const buf of buffers) + parser.write(buf); + parser.end(); + break; + } + + case 'formidable': { + const QuerystringParser = + require('formidable/src/parsers/Querystring.js'); + + console.time(moduleName); + const parser = new QuerystringParser(); + parser.on('data', (obj) => { + ++calls.field; + }).on('end', () => { + ++calls.end; + console.timeEnd(moduleName); + }); + + for (const buf of buffers) + parser.write(buf); + parser.end(); + break; + } + + case 'formidable-streaming': { + const QuerystringParser = + require('formidable/src/parsers/StreamingQuerystring.js'); + + console.time(moduleName); + const parser = new QuerystringParser(); + parser.on('data', (obj) => { + ++calls.field; + }).on('end', () => { + ++calls.end; + console.timeEnd(moduleName); + }); + + for (const buf of buffers) + parser.write(buf); + parser.end(); + break; + } + + default: + if (moduleName === undefined) + console.error('Missing parser module name'); + else + console.error(`Invalid parser module name: ${moduleName}`); + process.exit(1); +} diff --git a/node_modules/busboy/lib/index.js b/node_modules/busboy/lib/index.js new file mode 100644 index 0000000..873272d --- /dev/null +++ b/node_modules/busboy/lib/index.js @@ -0,0 +1,57 @@ +'use strict'; + +const { parseContentType } = require('./utils.js'); + +function getInstance(cfg) { + const headers = cfg.headers; + const conType = parseContentType(headers['content-type']); + if (!conType) + throw new Error('Malformed content type'); + + for (const type of TYPES) { + const matched = type.detect(conType); + if (!matched) + continue; + + const instanceCfg = { + limits: cfg.limits, + headers, + conType, + highWaterMark: undefined, + fileHwm: undefined, + defCharset: undefined, + defParamCharset: undefined, + preservePath: false, + }; + if (cfg.highWaterMark) + instanceCfg.highWaterMark = cfg.highWaterMark; + if (cfg.fileHwm) + instanceCfg.fileHwm = cfg.fileHwm; + instanceCfg.defCharset = cfg.defCharset; + instanceCfg.defParamCharset = cfg.defParamCharset; + instanceCfg.preservePath = cfg.preservePath; + return new type(instanceCfg); + } + + throw new Error(`Unsupported content type: ${headers['content-type']}`); +} + +// Note: types are explicitly listed here for easier bundling +// See: https://github.com/mscdex/busboy/issues/121 +const TYPES = [ + require('./types/multipart'), + require('./types/urlencoded'), +].filter(function(typemod) { return typeof typemod.detect === 'function'; }); + +module.exports = (cfg) => { + if (typeof cfg !== 'object' || cfg === null) + cfg = {}; + + if (typeof cfg.headers !== 'object' + || cfg.headers === null + || typeof cfg.headers['content-type'] !== 'string') { + throw new Error('Missing Content-Type'); + } + + return getInstance(cfg); +}; diff --git a/node_modules/busboy/lib/types/multipart.js b/node_modules/busboy/lib/types/multipart.js new file mode 100644 index 0000000..cc0d7bb --- /dev/null +++ b/node_modules/busboy/lib/types/multipart.js @@ -0,0 +1,653 @@ +'use strict'; + +const { Readable, Writable } = require('stream'); + +const StreamSearch = require('streamsearch'); + +const { + basename, + convertToUTF8, + getDecoder, + parseContentType, + parseDisposition, +} = require('../utils.js'); + +const BUF_CRLF = Buffer.from('\r\n'); +const BUF_CR = Buffer.from('\r'); +const BUF_DASH = Buffer.from('-'); + +function noop() {} + +const MAX_HEADER_PAIRS = 2000; // From node +const MAX_HEADER_SIZE = 16 * 1024; // From node (its default value) + +const HPARSER_NAME = 0; +const HPARSER_PRE_OWS = 1; +const HPARSER_VALUE = 2; +class HeaderParser { + constructor(cb) { + this.header = Object.create(null); + this.pairCount = 0; + this.byteCount = 0; + this.state = HPARSER_NAME; + this.name = ''; + this.value = ''; + this.crlf = 0; + this.cb = cb; + } + + reset() { + this.header = Object.create(null); + this.pairCount = 0; + this.byteCount = 0; + this.state = HPARSER_NAME; + this.name = ''; + this.value = ''; + this.crlf = 0; + } + + push(chunk, pos, end) { + let start = pos; + while (pos < end) { + switch (this.state) { + case HPARSER_NAME: { + let done = false; + for (; pos < end; ++pos) { + if (this.byteCount === MAX_HEADER_SIZE) + return -1; + ++this.byteCount; + const code = chunk[pos]; + if (TOKEN[code] !== 1) { + if (code !== 58/* ':' */) + return -1; + this.name += chunk.latin1Slice(start, pos); + if (this.name.length === 0) + return -1; + ++pos; + done = true; + this.state = HPARSER_PRE_OWS; + break; + } + } + if (!done) { + this.name += chunk.latin1Slice(start, pos); + break; + } + // FALLTHROUGH + } + case HPARSER_PRE_OWS: { + // Skip optional whitespace + let done = false; + for (; pos < end; ++pos) { + if (this.byteCount === MAX_HEADER_SIZE) + return -1; + ++this.byteCount; + const code = chunk[pos]; + if (code !== 32/* ' ' */ && code !== 9/* '\t' */) { + start = pos; + done = true; + this.state = HPARSER_VALUE; + break; + } + } + if (!done) + break; + // FALLTHROUGH + } + case HPARSER_VALUE: + switch (this.crlf) { + case 0: // Nothing yet + for (; pos < end; ++pos) { + if (this.byteCount === MAX_HEADER_SIZE) + return -1; + ++this.byteCount; + const code = chunk[pos]; + if (FIELD_VCHAR[code] !== 1) { + if (code !== 13/* '\r' */) + return -1; + ++this.crlf; + break; + } + } + this.value += chunk.latin1Slice(start, pos++); + break; + case 1: // Received CR + if (this.byteCount === MAX_HEADER_SIZE) + return -1; + ++this.byteCount; + if (chunk[pos++] !== 10/* '\n' */) + return -1; + ++this.crlf; + break; + case 2: { // Received CR LF + if (this.byteCount === MAX_HEADER_SIZE) + return -1; + ++this.byteCount; + const code = chunk[pos]; + if (code === 32/* ' ' */ || code === 9/* '\t' */) { + // Folded value + start = pos; + this.crlf = 0; + } else { + if (++this.pairCount < MAX_HEADER_PAIRS) { + this.name = this.name.toLowerCase(); + if (this.header[this.name] === undefined) + this.header[this.name] = [this.value]; + else + this.header[this.name].push(this.value); + } + if (code === 13/* '\r' */) { + ++this.crlf; + ++pos; + } else { + // Assume start of next header field name + start = pos; + this.crlf = 0; + this.state = HPARSER_NAME; + this.name = ''; + this.value = ''; + } + } + break; + } + case 3: { // Received CR LF CR + if (this.byteCount === MAX_HEADER_SIZE) + return -1; + ++this.byteCount; + if (chunk[pos++] !== 10/* '\n' */) + return -1; + // End of header + const header = this.header; + this.reset(); + this.cb(header); + return pos; + } + } + break; + } + } + + return pos; + } +} + +class FileStream extends Readable { + constructor(opts, owner) { + super(opts); + this.truncated = false; + this._readcb = null; + this.once('end', () => { + // We need to make sure that we call any outstanding _writecb() that is + // associated with this file so that processing of the rest of the form + // can continue. This may not happen if the file stream ends right after + // backpressure kicks in, so we force it here. + this._read(); + if (--owner._fileEndsLeft === 0 && owner._finalcb) { + const cb = owner._finalcb; + owner._finalcb = null; + // Make sure other 'end' event handlers get a chance to be executed + // before busboy's 'finish' event is emitted + process.nextTick(cb); + } + }); + } + _read(n) { + const cb = this._readcb; + if (cb) { + this._readcb = null; + cb(); + } + } +} + +const ignoreData = { + push: (chunk, pos) => {}, + destroy: () => {}, +}; + +function callAndUnsetCb(self, err) { + const cb = self._writecb; + self._writecb = null; + if (err) + self.destroy(err); + else if (cb) + cb(); +} + +function nullDecoder(val, hint) { + return val; +} + +class Multipart extends Writable { + constructor(cfg) { + const streamOpts = { + autoDestroy: true, + emitClose: true, + highWaterMark: (typeof cfg.highWaterMark === 'number' + ? cfg.highWaterMark + : undefined), + }; + super(streamOpts); + + if (!cfg.conType.params || typeof cfg.conType.params.boundary !== 'string') + throw new Error('Multipart: Boundary not found'); + + const boundary = cfg.conType.params.boundary; + const paramDecoder = (typeof cfg.defParamCharset === 'string' + && cfg.defParamCharset + ? getDecoder(cfg.defParamCharset) + : nullDecoder); + const defCharset = (cfg.defCharset || 'utf8'); + const preservePath = cfg.preservePath; + const fileOpts = { + autoDestroy: true, + emitClose: true, + highWaterMark: (typeof cfg.fileHwm === 'number' + ? cfg.fileHwm + : undefined), + }; + + const limits = cfg.limits; + const fieldSizeLimit = (limits && typeof limits.fieldSize === 'number' + ? limits.fieldSize + : 1 * 1024 * 1024); + const fileSizeLimit = (limits && typeof limits.fileSize === 'number' + ? limits.fileSize + : Infinity); + const filesLimit = (limits && typeof limits.files === 'number' + ? limits.files + : Infinity); + const fieldsLimit = (limits && typeof limits.fields === 'number' + ? limits.fields + : Infinity); + const partsLimit = (limits && typeof limits.parts === 'number' + ? limits.parts + : Infinity); + + let parts = -1; // Account for initial boundary + let fields = 0; + let files = 0; + let skipPart = false; + + this._fileEndsLeft = 0; + this._fileStream = undefined; + this._complete = false; + let fileSize = 0; + + let field; + let fieldSize = 0; + let partCharset; + let partEncoding; + let partType; + let partName; + let partTruncated = false; + + let hitFilesLimit = false; + let hitFieldsLimit = false; + + this._hparser = null; + const hparser = new HeaderParser((header) => { + this._hparser = null; + skipPart = false; + + partType = 'text/plain'; + partCharset = defCharset; + partEncoding = '7bit'; + partName = undefined; + partTruncated = false; + + let filename; + if (!header['content-disposition']) { + skipPart = true; + return; + } + + const disp = parseDisposition(header['content-disposition'][0], + paramDecoder); + if (!disp || disp.type !== 'form-data') { + skipPart = true; + return; + } + + if (disp.params) { + if (disp.params.name) + partName = disp.params.name; + + if (disp.params['filename*']) + filename = disp.params['filename*']; + else if (disp.params.filename) + filename = disp.params.filename; + + if (filename !== undefined && !preservePath) + filename = basename(filename); + } + + if (header['content-type']) { + const conType = parseContentType(header['content-type'][0]); + if (conType) { + partType = `${conType.type}/${conType.subtype}`; + if (conType.params && typeof conType.params.charset === 'string') + partCharset = conType.params.charset.toLowerCase(); + } + } + + if (header['content-transfer-encoding']) + partEncoding = header['content-transfer-encoding'][0].toLowerCase(); + + if (partType === 'application/octet-stream' || filename !== undefined) { + // File + + if (files === filesLimit) { + if (!hitFilesLimit) { + hitFilesLimit = true; + this.emit('filesLimit'); + } + skipPart = true; + return; + } + ++files; + + if (this.listenerCount('file') === 0) { + skipPart = true; + return; + } + + fileSize = 0; + this._fileStream = new FileStream(fileOpts, this); + ++this._fileEndsLeft; + this.emit( + 'file', + partName, + this._fileStream, + { filename, + encoding: partEncoding, + mimeType: partType } + ); + } else { + // Non-file + + if (fields === fieldsLimit) { + if (!hitFieldsLimit) { + hitFieldsLimit = true; + this.emit('fieldsLimit'); + } + skipPart = true; + return; + } + ++fields; + + if (this.listenerCount('field') === 0) { + skipPart = true; + return; + } + + field = []; + fieldSize = 0; + } + }); + + let matchPostBoundary = 0; + const ssCb = (isMatch, data, start, end, isDataSafe) => { +retrydata: + while (data) { + if (this._hparser !== null) { + const ret = this._hparser.push(data, start, end); + if (ret === -1) { + this._hparser = null; + hparser.reset(); + this.emit('error', new Error('Malformed part header')); + break; + } + start = ret; + } + + if (start === end) + break; + + if (matchPostBoundary !== 0) { + if (matchPostBoundary === 1) { + switch (data[start]) { + case 45: // '-' + // Try matching '--' after boundary + matchPostBoundary = 2; + ++start; + break; + case 13: // '\r' + // Try matching CR LF before header + matchPostBoundary = 3; + ++start; + break; + default: + matchPostBoundary = 0; + } + if (start === end) + return; + } + + if (matchPostBoundary === 2) { + matchPostBoundary = 0; + if (data[start] === 45/* '-' */) { + // End of multipart data + this._complete = true; + this._bparser = ignoreData; + return; + } + // We saw something other than '-', so put the dash we consumed + // "back" + const writecb = this._writecb; + this._writecb = noop; + ssCb(false, BUF_DASH, 0, 1, false); + this._writecb = writecb; + } else if (matchPostBoundary === 3) { + matchPostBoundary = 0; + if (data[start] === 10/* '\n' */) { + ++start; + if (parts >= partsLimit) + break; + // Prepare the header parser + this._hparser = hparser; + if (start === end) + break; + // Process the remaining data as a header + continue retrydata; + } else { + // We saw something other than LF, so put the CR we consumed + // "back" + const writecb = this._writecb; + this._writecb = noop; + ssCb(false, BUF_CR, 0, 1, false); + this._writecb = writecb; + } + } + } + + if (!skipPart) { + if (this._fileStream) { + let chunk; + const actualLen = Math.min(end - start, fileSizeLimit - fileSize); + if (!isDataSafe) { + chunk = Buffer.allocUnsafe(actualLen); + data.copy(chunk, 0, start, start + actualLen); + } else { + chunk = data.slice(start, start + actualLen); + } + + fileSize += chunk.length; + if (fileSize === fileSizeLimit) { + if (chunk.length > 0) + this._fileStream.push(chunk); + this._fileStream.emit('limit'); + this._fileStream.truncated = true; + skipPart = true; + } else if (!this._fileStream.push(chunk)) { + if (this._writecb) + this._fileStream._readcb = this._writecb; + this._writecb = null; + } + } else if (field !== undefined) { + let chunk; + const actualLen = Math.min( + end - start, + fieldSizeLimit - fieldSize + ); + if (!isDataSafe) { + chunk = Buffer.allocUnsafe(actualLen); + data.copy(chunk, 0, start, start + actualLen); + } else { + chunk = data.slice(start, start + actualLen); + } + + fieldSize += actualLen; + field.push(chunk); + if (fieldSize === fieldSizeLimit) { + skipPart = true; + partTruncated = true; + } + } + } + + break; + } + + if (isMatch) { + matchPostBoundary = 1; + + if (this._fileStream) { + // End the active file stream if the previous part was a file + this._fileStream.push(null); + this._fileStream = null; + } else if (field !== undefined) { + let data; + switch (field.length) { + case 0: + data = ''; + break; + case 1: + data = convertToUTF8(field[0], partCharset, 0); + break; + default: + data = convertToUTF8( + Buffer.concat(field, fieldSize), + partCharset, + 0 + ); + } + field = undefined; + fieldSize = 0; + this.emit( + 'field', + partName, + data, + { nameTruncated: false, + valueTruncated: partTruncated, + encoding: partEncoding, + mimeType: partType } + ); + } + + if (++parts === partsLimit) + this.emit('partsLimit'); + } + }; + this._bparser = new StreamSearch(`\r\n--${boundary}`, ssCb); + + this._writecb = null; + this._finalcb = null; + + // Just in case there is no preamble + this.write(BUF_CRLF); + } + + static detect(conType) { + return (conType.type === 'multipart' && conType.subtype === 'form-data'); + } + + _write(chunk, enc, cb) { + this._writecb = cb; + this._bparser.push(chunk, 0); + if (this._writecb) + callAndUnsetCb(this); + } + + _destroy(err, cb) { + this._hparser = null; + this._bparser = ignoreData; + if (!err) + err = checkEndState(this); + const fileStream = this._fileStream; + if (fileStream) { + this._fileStream = null; + fileStream.destroy(err); + } + cb(err); + } + + _final(cb) { + this._bparser.destroy(); + if (!this._complete) + return cb(new Error('Unexpected end of form')); + if (this._fileEndsLeft) + this._finalcb = finalcb.bind(null, this, cb); + else + finalcb(this, cb); + } +} + +function finalcb(self, cb, err) { + if (err) + return cb(err); + err = checkEndState(self); + cb(err); +} + +function checkEndState(self) { + if (self._hparser) + return new Error('Malformed part header'); + const fileStream = self._fileStream; + if (fileStream) { + self._fileStream = null; + fileStream.destroy(new Error('Unexpected end of file')); + } + if (!self._complete) + return new Error('Unexpected end of form'); +} + +const TOKEN = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +]; + +const FIELD_VCHAR = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, +]; + +module.exports = Multipart; diff --git a/node_modules/busboy/lib/types/urlencoded.js b/node_modules/busboy/lib/types/urlencoded.js new file mode 100644 index 0000000..5c463a2 --- /dev/null +++ b/node_modules/busboy/lib/types/urlencoded.js @@ -0,0 +1,350 @@ +'use strict'; + +const { Writable } = require('stream'); + +const { getDecoder } = require('../utils.js'); + +class URLEncoded extends Writable { + constructor(cfg) { + const streamOpts = { + autoDestroy: true, + emitClose: true, + highWaterMark: (typeof cfg.highWaterMark === 'number' + ? cfg.highWaterMark + : undefined), + }; + super(streamOpts); + + let charset = (cfg.defCharset || 'utf8'); + if (cfg.conType.params && typeof cfg.conType.params.charset === 'string') + charset = cfg.conType.params.charset; + + this.charset = charset; + + const limits = cfg.limits; + this.fieldSizeLimit = (limits && typeof limits.fieldSize === 'number' + ? limits.fieldSize + : 1 * 1024 * 1024); + this.fieldsLimit = (limits && typeof limits.fields === 'number' + ? limits.fields + : Infinity); + this.fieldNameSizeLimit = ( + limits && typeof limits.fieldNameSize === 'number' + ? limits.fieldNameSize + : 100 + ); + + this._inKey = true; + this._keyTrunc = false; + this._valTrunc = false; + this._bytesKey = 0; + this._bytesVal = 0; + this._fields = 0; + this._key = ''; + this._val = ''; + this._byte = -2; + this._lastPos = 0; + this._encode = 0; + this._decoder = getDecoder(charset); + } + + static detect(conType) { + return (conType.type === 'application' + && conType.subtype === 'x-www-form-urlencoded'); + } + + _write(chunk, enc, cb) { + if (this._fields >= this.fieldsLimit) + return cb(); + + let i = 0; + const len = chunk.length; + this._lastPos = 0; + + // Check if we last ended mid-percent-encoded byte + if (this._byte !== -2) { + i = readPctEnc(this, chunk, i, len); + if (i === -1) + return cb(new Error('Malformed urlencoded form')); + if (i >= len) + return cb(); + if (this._inKey) + ++this._bytesKey; + else + ++this._bytesVal; + } + +main: + while (i < len) { + if (this._inKey) { + // Parsing key + + i = skipKeyBytes(this, chunk, i, len); + + while (i < len) { + switch (chunk[i]) { + case 61: // '=' + if (this._lastPos < i) + this._key += chunk.latin1Slice(this._lastPos, i); + this._lastPos = ++i; + this._key = this._decoder(this._key, this._encode); + this._encode = 0; + this._inKey = false; + continue main; + case 38: // '&' + if (this._lastPos < i) + this._key += chunk.latin1Slice(this._lastPos, i); + this._lastPos = ++i; + this._key = this._decoder(this._key, this._encode); + this._encode = 0; + if (this._bytesKey > 0) { + this.emit( + 'field', + this._key, + '', + { nameTruncated: this._keyTrunc, + valueTruncated: false, + encoding: this.charset, + mimeType: 'text/plain' } + ); + } + this._key = ''; + this._val = ''; + this._keyTrunc = false; + this._valTrunc = false; + this._bytesKey = 0; + this._bytesVal = 0; + if (++this._fields >= this.fieldsLimit) { + this.emit('fieldsLimit'); + return cb(); + } + continue; + case 43: // '+' + if (this._lastPos < i) + this._key += chunk.latin1Slice(this._lastPos, i); + this._key += ' '; + this._lastPos = i + 1; + break; + case 37: // '%' + if (this._encode === 0) + this._encode = 1; + if (this._lastPos < i) + this._key += chunk.latin1Slice(this._lastPos, i); + this._lastPos = i + 1; + this._byte = -1; + i = readPctEnc(this, chunk, i + 1, len); + if (i === -1) + return cb(new Error('Malformed urlencoded form')); + if (i >= len) + return cb(); + ++this._bytesKey; + i = skipKeyBytes(this, chunk, i, len); + continue; + } + ++i; + ++this._bytesKey; + i = skipKeyBytes(this, chunk, i, len); + } + if (this._lastPos < i) + this._key += chunk.latin1Slice(this._lastPos, i); + } else { + // Parsing value + + i = skipValBytes(this, chunk, i, len); + + while (i < len) { + switch (chunk[i]) { + case 38: // '&' + if (this._lastPos < i) + this._val += chunk.latin1Slice(this._lastPos, i); + this._lastPos = ++i; + this._inKey = true; + this._val = this._decoder(this._val, this._encode); + this._encode = 0; + if (this._bytesKey > 0 || this._bytesVal > 0) { + this.emit( + 'field', + this._key, + this._val, + { nameTruncated: this._keyTrunc, + valueTruncated: this._valTrunc, + encoding: this.charset, + mimeType: 'text/plain' } + ); + } + this._key = ''; + this._val = ''; + this._keyTrunc = false; + this._valTrunc = false; + this._bytesKey = 0; + this._bytesVal = 0; + if (++this._fields >= this.fieldsLimit) { + this.emit('fieldsLimit'); + return cb(); + } + continue main; + case 43: // '+' + if (this._lastPos < i) + this._val += chunk.latin1Slice(this._lastPos, i); + this._val += ' '; + this._lastPos = i + 1; + break; + case 37: // '%' + if (this._encode === 0) + this._encode = 1; + if (this._lastPos < i) + this._val += chunk.latin1Slice(this._lastPos, i); + this._lastPos = i + 1; + this._byte = -1; + i = readPctEnc(this, chunk, i + 1, len); + if (i === -1) + return cb(new Error('Malformed urlencoded form')); + if (i >= len) + return cb(); + ++this._bytesVal; + i = skipValBytes(this, chunk, i, len); + continue; + } + ++i; + ++this._bytesVal; + i = skipValBytes(this, chunk, i, len); + } + if (this._lastPos < i) + this._val += chunk.latin1Slice(this._lastPos, i); + } + } + + cb(); + } + + _final(cb) { + if (this._byte !== -2) + return cb(new Error('Malformed urlencoded form')); + if (!this._inKey || this._bytesKey > 0 || this._bytesVal > 0) { + if (this._inKey) + this._key = this._decoder(this._key, this._encode); + else + this._val = this._decoder(this._val, this._encode); + this.emit( + 'field', + this._key, + this._val, + { nameTruncated: this._keyTrunc, + valueTruncated: this._valTrunc, + encoding: this.charset, + mimeType: 'text/plain' } + ); + } + cb(); + } +} + +function readPctEnc(self, chunk, pos, len) { + if (pos >= len) + return len; + + if (self._byte === -1) { + // We saw a '%' but no hex characters yet + const hexUpper = HEX_VALUES[chunk[pos++]]; + if (hexUpper === -1) + return -1; + + if (hexUpper >= 8) + self._encode = 2; // Indicate high bits detected + + if (pos < len) { + // Both hex characters are in this chunk + const hexLower = HEX_VALUES[chunk[pos++]]; + if (hexLower === -1) + return -1; + + if (self._inKey) + self._key += String.fromCharCode((hexUpper << 4) + hexLower); + else + self._val += String.fromCharCode((hexUpper << 4) + hexLower); + + self._byte = -2; + self._lastPos = pos; + } else { + // Only one hex character was available in this chunk + self._byte = hexUpper; + } + } else { + // We saw only one hex character so far + const hexLower = HEX_VALUES[chunk[pos++]]; + if (hexLower === -1) + return -1; + + if (self._inKey) + self._key += String.fromCharCode((self._byte << 4) + hexLower); + else + self._val += String.fromCharCode((self._byte << 4) + hexLower); + + self._byte = -2; + self._lastPos = pos; + } + + return pos; +} + +function skipKeyBytes(self, chunk, pos, len) { + // Skip bytes if we've truncated + if (self._bytesKey > self.fieldNameSizeLimit) { + if (!self._keyTrunc) { + if (self._lastPos < pos) + self._key += chunk.latin1Slice(self._lastPos, pos - 1); + } + self._keyTrunc = true; + for (; pos < len; ++pos) { + const code = chunk[pos]; + if (code === 61/* '=' */ || code === 38/* '&' */) + break; + ++self._bytesKey; + } + self._lastPos = pos; + } + + return pos; +} + +function skipValBytes(self, chunk, pos, len) { + // Skip bytes if we've truncated + if (self._bytesVal > self.fieldSizeLimit) { + if (!self._valTrunc) { + if (self._lastPos < pos) + self._val += chunk.latin1Slice(self._lastPos, pos - 1); + } + self._valTrunc = true; + for (; pos < len; ++pos) { + if (chunk[pos] === 38/* '&' */) + break; + ++self._bytesVal; + } + self._lastPos = pos; + } + + return pos; +} + +/* eslint-disable no-multi-spaces */ +const HEX_VALUES = [ + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, + -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, +]; +/* eslint-enable no-multi-spaces */ + +module.exports = URLEncoded; diff --git a/node_modules/busboy/lib/utils.js b/node_modules/busboy/lib/utils.js new file mode 100644 index 0000000..8274f6c --- /dev/null +++ b/node_modules/busboy/lib/utils.js @@ -0,0 +1,596 @@ +'use strict'; + +function parseContentType(str) { + if (str.length === 0) + return; + + const params = Object.create(null); + let i = 0; + + // Parse type + for (; i < str.length; ++i) { + const code = str.charCodeAt(i); + if (TOKEN[code] !== 1) { + if (code !== 47/* '/' */ || i === 0) + return; + break; + } + } + // Check for type without subtype + if (i === str.length) + return; + + const type = str.slice(0, i).toLowerCase(); + + // Parse subtype + const subtypeStart = ++i; + for (; i < str.length; ++i) { + const code = str.charCodeAt(i); + if (TOKEN[code] !== 1) { + // Make sure we have a subtype + if (i === subtypeStart) + return; + + if (parseContentTypeParams(str, i, params) === undefined) + return; + break; + } + } + // Make sure we have a subtype + if (i === subtypeStart) + return; + + const subtype = str.slice(subtypeStart, i).toLowerCase(); + + return { type, subtype, params }; +} + +function parseContentTypeParams(str, i, params) { + while (i < str.length) { + // Consume whitespace + for (; i < str.length; ++i) { + const code = str.charCodeAt(i); + if (code !== 32/* ' ' */ && code !== 9/* '\t' */) + break; + } + + // Ended on whitespace + if (i === str.length) + break; + + // Check for malformed parameter + if (str.charCodeAt(i++) !== 59/* ';' */) + return; + + // Consume whitespace + for (; i < str.length; ++i) { + const code = str.charCodeAt(i); + if (code !== 32/* ' ' */ && code !== 9/* '\t' */) + break; + } + + // Ended on whitespace (malformed) + if (i === str.length) + return; + + let name; + const nameStart = i; + // Parse parameter name + for (; i < str.length; ++i) { + const code = str.charCodeAt(i); + if (TOKEN[code] !== 1) { + if (code !== 61/* '=' */) + return; + break; + } + } + + // No value (malformed) + if (i === str.length) + return; + + name = str.slice(nameStart, i); + ++i; // Skip over '=' + + // No value (malformed) + if (i === str.length) + return; + + let value = ''; + let valueStart; + if (str.charCodeAt(i) === 34/* '"' */) { + valueStart = ++i; + let escaping = false; + // Parse quoted value + for (; i < str.length; ++i) { + const code = str.charCodeAt(i); + if (code === 92/* '\\' */) { + if (escaping) { + valueStart = i; + escaping = false; + } else { + value += str.slice(valueStart, i); + escaping = true; + } + continue; + } + if (code === 34/* '"' */) { + if (escaping) { + valueStart = i; + escaping = false; + continue; + } + value += str.slice(valueStart, i); + break; + } + if (escaping) { + valueStart = i - 1; + escaping = false; + } + // Invalid unescaped quoted character (malformed) + if (QDTEXT[code] !== 1) + return; + } + + // No end quote (malformed) + if (i === str.length) + return; + + ++i; // Skip over double quote + } else { + valueStart = i; + // Parse unquoted value + for (; i < str.length; ++i) { + const code = str.charCodeAt(i); + if (TOKEN[code] !== 1) { + // No value (malformed) + if (i === valueStart) + return; + break; + } + } + value = str.slice(valueStart, i); + } + + name = name.toLowerCase(); + if (params[name] === undefined) + params[name] = value; + } + + return params; +} + +function parseDisposition(str, defDecoder) { + if (str.length === 0) + return; + + const params = Object.create(null); + let i = 0; + + for (; i < str.length; ++i) { + const code = str.charCodeAt(i); + if (TOKEN[code] !== 1) { + if (parseDispositionParams(str, i, params, defDecoder) === undefined) + return; + break; + } + } + + const type = str.slice(0, i).toLowerCase(); + + return { type, params }; +} + +function parseDispositionParams(str, i, params, defDecoder) { + while (i < str.length) { + // Consume whitespace + for (; i < str.length; ++i) { + const code = str.charCodeAt(i); + if (code !== 32/* ' ' */ && code !== 9/* '\t' */) + break; + } + + // Ended on whitespace + if (i === str.length) + break; + + // Check for malformed parameter + if (str.charCodeAt(i++) !== 59/* ';' */) + return; + + // Consume whitespace + for (; i < str.length; ++i) { + const code = str.charCodeAt(i); + if (code !== 32/* ' ' */ && code !== 9/* '\t' */) + break; + } + + // Ended on whitespace (malformed) + if (i === str.length) + return; + + let name; + const nameStart = i; + // Parse parameter name + for (; i < str.length; ++i) { + const code = str.charCodeAt(i); + if (TOKEN[code] !== 1) { + if (code === 61/* '=' */) + break; + return; + } + } + + // No value (malformed) + if (i === str.length) + return; + + let value = ''; + let valueStart; + let charset; + //~ let lang; + name = str.slice(nameStart, i); + if (name.charCodeAt(name.length - 1) === 42/* '*' */) { + // Extended value + + const charsetStart = ++i; + // Parse charset name + for (; i < str.length; ++i) { + const code = str.charCodeAt(i); + if (CHARSET[code] !== 1) { + if (code !== 39/* '\'' */) + return; + break; + } + } + + // Incomplete charset (malformed) + if (i === str.length) + return; + + charset = str.slice(charsetStart, i); + ++i; // Skip over the '\'' + + //~ const langStart = ++i; + // Parse language name + for (; i < str.length; ++i) { + const code = str.charCodeAt(i); + if (code === 39/* '\'' */) + break; + } + + // Incomplete language (malformed) + if (i === str.length) + return; + + //~ lang = str.slice(langStart, i); + ++i; // Skip over the '\'' + + // No value (malformed) + if (i === str.length) + return; + + valueStart = i; + + let encode = 0; + // Parse value + for (; i < str.length; ++i) { + const code = str.charCodeAt(i); + if (EXTENDED_VALUE[code] !== 1) { + if (code === 37/* '%' */) { + let hexUpper; + let hexLower; + if (i + 2 < str.length + && (hexUpper = HEX_VALUES[str.charCodeAt(i + 1)]) !== -1 + && (hexLower = HEX_VALUES[str.charCodeAt(i + 2)]) !== -1) { + const byteVal = (hexUpper << 4) + hexLower; + value += str.slice(valueStart, i); + value += String.fromCharCode(byteVal); + i += 2; + valueStart = i + 1; + if (byteVal >= 128) + encode = 2; + else if (encode === 0) + encode = 1; + continue; + } + // '%' disallowed in non-percent encoded contexts (malformed) + return; + } + break; + } + } + + value += str.slice(valueStart, i); + value = convertToUTF8(value, charset, encode); + if (value === undefined) + return; + } else { + // Non-extended value + + ++i; // Skip over '=' + + // No value (malformed) + if (i === str.length) + return; + + if (str.charCodeAt(i) === 34/* '"' */) { + valueStart = ++i; + let escaping = false; + // Parse quoted value + for (; i < str.length; ++i) { + const code = str.charCodeAt(i); + if (code === 92/* '\\' */) { + if (escaping) { + valueStart = i; + escaping = false; + } else { + value += str.slice(valueStart, i); + escaping = true; + } + continue; + } + if (code === 34/* '"' */) { + if (escaping) { + valueStart = i; + escaping = false; + continue; + } + value += str.slice(valueStart, i); + break; + } + if (escaping) { + valueStart = i - 1; + escaping = false; + } + // Invalid unescaped quoted character (malformed) + if (QDTEXT[code] !== 1) + return; + } + + // No end quote (malformed) + if (i === str.length) + return; + + ++i; // Skip over double quote + } else { + valueStart = i; + // Parse unquoted value + for (; i < str.length; ++i) { + const code = str.charCodeAt(i); + if (TOKEN[code] !== 1) { + // No value (malformed) + if (i === valueStart) + return; + break; + } + } + value = str.slice(valueStart, i); + } + + value = defDecoder(value, 2); + if (value === undefined) + return; + } + + name = name.toLowerCase(); + if (params[name] === undefined) + params[name] = value; + } + + return params; +} + +function getDecoder(charset) { + let lc; + while (true) { + switch (charset) { + case 'utf-8': + case 'utf8': + return decoders.utf8; + case 'latin1': + case 'ascii': // TODO: Make these a separate, strict decoder? + case 'us-ascii': + case 'iso-8859-1': + case 'iso8859-1': + case 'iso88591': + case 'iso_8859-1': + case 'windows-1252': + case 'iso_8859-1:1987': + case 'cp1252': + case 'x-cp1252': + return decoders.latin1; + case 'utf16le': + case 'utf-16le': + case 'ucs2': + case 'ucs-2': + return decoders.utf16le; + case 'base64': + return decoders.base64; + default: + if (lc === undefined) { + lc = true; + charset = charset.toLowerCase(); + continue; + } + return decoders.other.bind(charset); + } + } +} + +const decoders = { + utf8: (data, hint) => { + if (data.length === 0) + return ''; + if (typeof data === 'string') { + // If `data` never had any percent-encoded bytes or never had any that + // were outside of the ASCII range, then we can safely just return the + // input since UTF-8 is ASCII compatible + if (hint < 2) + return data; + + data = Buffer.from(data, 'latin1'); + } + return data.utf8Slice(0, data.length); + }, + + latin1: (data, hint) => { + if (data.length === 0) + return ''; + if (typeof data === 'string') + return data; + return data.latin1Slice(0, data.length); + }, + + utf16le: (data, hint) => { + if (data.length === 0) + return ''; + if (typeof data === 'string') + data = Buffer.from(data, 'latin1'); + return data.ucs2Slice(0, data.length); + }, + + base64: (data, hint) => { + if (data.length === 0) + return ''; + if (typeof data === 'string') + data = Buffer.from(data, 'latin1'); + return data.base64Slice(0, data.length); + }, + + other: (data, hint) => { + if (data.length === 0) + return ''; + if (typeof data === 'string') + data = Buffer.from(data, 'latin1'); + try { + const decoder = new TextDecoder(this); + return decoder.decode(data); + } catch {} + }, +}; + +function convertToUTF8(data, charset, hint) { + const decode = getDecoder(charset); + if (decode) + return decode(data, hint); +} + +function basename(path) { + if (typeof path !== 'string') + return ''; + for (let i = path.length - 1; i >= 0; --i) { + switch (path.charCodeAt(i)) { + case 0x2F: // '/' + case 0x5C: // '\' + path = path.slice(i + 1); + return (path === '..' || path === '.' ? '' : path); + } + } + return (path === '..' || path === '.' ? '' : path); +} + +const TOKEN = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +]; + +const QDTEXT = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, +]; + +const CHARSET = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +]; + +const EXTENDED_VALUE = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +]; + +/* eslint-disable no-multi-spaces */ +const HEX_VALUES = [ + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, + -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, +]; +/* eslint-enable no-multi-spaces */ + +module.exports = { + basename, + convertToUTF8, + getDecoder, + parseContentType, + parseDisposition, +}; diff --git a/node_modules/busboy/package.json b/node_modules/busboy/package.json new file mode 100644 index 0000000..ac2577f --- /dev/null +++ b/node_modules/busboy/package.json @@ -0,0 +1,22 @@ +{ "name": "busboy", + "version": "1.6.0", + "author": "Brian White ", + "description": "A streaming parser for HTML form data for node.js", + "main": "./lib/index.js", + "dependencies": { + "streamsearch": "^1.1.0" + }, + "devDependencies": { + "@mscdex/eslint-config": "^1.1.0", + "eslint": "^7.32.0" + }, + "scripts": { + "test": "node test/test.js", + "lint": "eslint --cache --report-unused-disable-directives --ext=.js .eslintrc.js lib test bench", + "lint:fix": "npm run lint -- --fix" + }, + "engines": { "node": ">=10.16.0" }, + "keywords": [ "uploads", "forms", "multipart", "form-data" ], + "licenses": [ { "type": "MIT", "url": "http://github.com/mscdex/busboy/raw/master/LICENSE" } ], + "repository": { "type": "git", "url": "http://github.com/mscdex/busboy.git" } +} diff --git a/node_modules/busboy/test/common.js b/node_modules/busboy/test/common.js new file mode 100644 index 0000000..fb82ad8 --- /dev/null +++ b/node_modules/busboy/test/common.js @@ -0,0 +1,109 @@ +'use strict'; + +const assert = require('assert'); +const { inspect } = require('util'); + +const mustCallChecks = []; + +function noop() {} + +function runCallChecks(exitCode) { + if (exitCode !== 0) return; + + const failed = mustCallChecks.filter((context) => { + if ('minimum' in context) { + context.messageSegment = `at least ${context.minimum}`; + return context.actual < context.minimum; + } + context.messageSegment = `exactly ${context.exact}`; + return context.actual !== context.exact; + }); + + failed.forEach((context) => { + console.error('Mismatched %s function calls. Expected %s, actual %d.', + context.name, + context.messageSegment, + context.actual); + console.error(context.stack.split('\n').slice(2).join('\n')); + }); + + if (failed.length) + process.exit(1); +} + +function mustCall(fn, exact) { + return _mustCallInner(fn, exact, 'exact'); +} + +function mustCallAtLeast(fn, minimum) { + return _mustCallInner(fn, minimum, 'minimum'); +} + +function _mustCallInner(fn, criteria = 1, field) { + if (process._exiting) + throw new Error('Cannot use common.mustCall*() in process exit handler'); + + if (typeof fn === 'number') { + criteria = fn; + fn = noop; + } else if (fn === undefined) { + fn = noop; + } + + if (typeof criteria !== 'number') + throw new TypeError(`Invalid ${field} value: ${criteria}`); + + const context = { + [field]: criteria, + actual: 0, + stack: inspect(new Error()), + name: fn.name || '' + }; + + // Add the exit listener only once to avoid listener leak warnings + if (mustCallChecks.length === 0) + process.on('exit', runCallChecks); + + mustCallChecks.push(context); + + function wrapped(...args) { + ++context.actual; + return fn.call(this, ...args); + } + // TODO: remove origFn? + wrapped.origFn = fn; + + return wrapped; +} + +function getCallSite(top) { + const originalStackFormatter = Error.prepareStackTrace; + Error.prepareStackTrace = (err, stack) => + `${stack[0].getFileName()}:${stack[0].getLineNumber()}`; + const err = new Error(); + Error.captureStackTrace(err, top); + // With the V8 Error API, the stack is not formatted until it is accessed + // eslint-disable-next-line no-unused-expressions + err.stack; + Error.prepareStackTrace = originalStackFormatter; + return err.stack; +} + +function mustNotCall(msg) { + const callSite = getCallSite(mustNotCall); + return function mustNotCall(...args) { + args = args.map(inspect).join(', '); + const argsInfo = (args.length > 0 + ? `\ncalled with arguments: ${args}` + : ''); + assert.fail( + `${msg || 'function should not have been called'} at ${callSite}` + + argsInfo); + }; +} + +module.exports = { + mustCall, + mustCallAtLeast, + mustNotCall, +}; diff --git a/node_modules/busboy/test/test-types-multipart-charsets.js b/node_modules/busboy/test/test-types-multipart-charsets.js new file mode 100644 index 0000000..ed9c38a --- /dev/null +++ b/node_modules/busboy/test/test-types-multipart-charsets.js @@ -0,0 +1,94 @@ +'use strict'; + +const assert = require('assert'); +const { inspect } = require('util'); + +const { mustCall } = require(`${__dirname}/common.js`); + +const busboy = require('..'); + +const input = Buffer.from([ + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_0"; filename="テスト.dat"', + 'Content-Type: application/octet-stream', + '', + 'A'.repeat(1023), + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--' +].join('\r\n')); +const boundary = '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k'; +const expected = [ + { type: 'file', + name: 'upload_file_0', + data: Buffer.from('A'.repeat(1023)), + info: { + filename: 'テスト.dat', + encoding: '7bit', + mimeType: 'application/octet-stream', + }, + limited: false, + }, +]; +const bb = busboy({ + defParamCharset: 'utf8', + headers: { + 'content-type': `multipart/form-data; boundary=${boundary}`, + } +}); +const results = []; + +bb.on('field', (name, val, info) => { + results.push({ type: 'field', name, val, info }); +}); + +bb.on('file', (name, stream, info) => { + const data = []; + let nb = 0; + const file = { + type: 'file', + name, + data: null, + info, + limited: false, + }; + results.push(file); + stream.on('data', (d) => { + data.push(d); + nb += d.length; + }).on('limit', () => { + file.limited = true; + }).on('close', () => { + file.data = Buffer.concat(data, nb); + assert.strictEqual(stream.truncated, file.limited); + }).once('error', (err) => { + file.err = err.message; + }); +}); + +bb.on('error', (err) => { + results.push({ error: err.message }); +}); + +bb.on('partsLimit', () => { + results.push('partsLimit'); +}); + +bb.on('filesLimit', () => { + results.push('filesLimit'); +}); + +bb.on('fieldsLimit', () => { + results.push('fieldsLimit'); +}); + +bb.on('close', mustCall(() => { + assert.deepStrictEqual( + results, + expected, + 'Results mismatch.\n' + + `Parsed: ${inspect(results)}\n` + + `Expected: ${inspect(expected)}` + ); +})); + +bb.end(input); diff --git a/node_modules/busboy/test/test-types-multipart-stream-pause.js b/node_modules/busboy/test/test-types-multipart-stream-pause.js new file mode 100644 index 0000000..df7268a --- /dev/null +++ b/node_modules/busboy/test/test-types-multipart-stream-pause.js @@ -0,0 +1,102 @@ +'use strict'; + +const assert = require('assert'); +const { randomFillSync } = require('crypto'); +const { inspect } = require('util'); + +const busboy = require('..'); + +const { mustCall } = require('./common.js'); + +const BOUNDARY = 'u2KxIV5yF1y+xUspOQCCZopaVgeV6Jxihv35XQJmuTx8X3sh'; + +function formDataSection(key, value) { + return Buffer.from( + `\r\n--${BOUNDARY}` + + `\r\nContent-Disposition: form-data; name="${key}"` + + `\r\n\r\n${value}` + ); +} + +function formDataFile(key, filename, contentType) { + const buf = Buffer.allocUnsafe(100000); + return Buffer.concat([ + Buffer.from(`\r\n--${BOUNDARY}\r\n`), + Buffer.from(`Content-Disposition: form-data; name="${key}"` + + `; filename="${filename}"\r\n`), + Buffer.from(`Content-Type: ${contentType}\r\n\r\n`), + randomFillSync(buf) + ]); +} + +const reqChunks = [ + Buffer.concat([ + formDataFile('file', 'file.bin', 'application/octet-stream'), + formDataSection('foo', 'foo value'), + ]), + formDataSection('bar', 'bar value'), + Buffer.from(`\r\n--${BOUNDARY}--\r\n`) +]; +const bb = busboy({ + headers: { + 'content-type': `multipart/form-data; boundary=${BOUNDARY}` + } +}); +const expected = [ + { type: 'file', + name: 'file', + info: { + filename: 'file.bin', + encoding: '7bit', + mimeType: 'application/octet-stream', + }, + }, + { type: 'field', + name: 'foo', + val: 'foo value', + info: { + nameTruncated: false, + valueTruncated: false, + encoding: '7bit', + mimeType: 'text/plain', + }, + }, + { type: 'field', + name: 'bar', + val: 'bar value', + info: { + nameTruncated: false, + valueTruncated: false, + encoding: '7bit', + mimeType: 'text/plain', + }, + }, +]; +const results = []; + +bb.on('field', (name, val, info) => { + results.push({ type: 'field', name, val, info }); +}); + +bb.on('file', (name, stream, info) => { + results.push({ type: 'file', name, info }); + // Simulate a pipe where the destination is pausing (perhaps due to waiting + // for file system write to finish) + setTimeout(() => { + stream.resume(); + }, 10); +}); + +bb.on('close', mustCall(() => { + assert.deepStrictEqual( + results, + expected, + 'Results mismatch.\n' + + `Parsed: ${inspect(results)}\n` + + `Expected: ${inspect(expected)}` + ); +})); + +for (const chunk of reqChunks) + bb.write(chunk); +bb.end(); diff --git a/node_modules/busboy/test/test-types-multipart.js b/node_modules/busboy/test/test-types-multipart.js new file mode 100644 index 0000000..9755642 --- /dev/null +++ b/node_modules/busboy/test/test-types-multipart.js @@ -0,0 +1,1053 @@ +'use strict'; + +const assert = require('assert'); +const { inspect } = require('util'); + +const busboy = require('..'); + +const active = new Map(); + +const tests = [ + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; name="file_name_0"', + '', + 'super alpha file', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; name="file_name_1"', + '', + 'super beta file', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_0"; filename="1k_a.dat"', + 'Content-Type: application/octet-stream', + '', + 'A'.repeat(1023), + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_1"; filename="1k_b.dat"', + 'Content-Type: application/octet-stream', + '', + 'B'.repeat(1023), + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--' + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + expected: [ + { type: 'field', + name: 'file_name_0', + val: 'super alpha file', + info: { + nameTruncated: false, + valueTruncated: false, + encoding: '7bit', + mimeType: 'text/plain', + }, + }, + { type: 'field', + name: 'file_name_1', + val: 'super beta file', + info: { + nameTruncated: false, + valueTruncated: false, + encoding: '7bit', + mimeType: 'text/plain', + }, + }, + { type: 'file', + name: 'upload_file_0', + data: Buffer.from('A'.repeat(1023)), + info: { + filename: '1k_a.dat', + encoding: '7bit', + mimeType: 'application/octet-stream', + }, + limited: false, + }, + { type: 'file', + name: 'upload_file_1', + data: Buffer.from('B'.repeat(1023)), + info: { + filename: '1k_b.dat', + encoding: '7bit', + mimeType: 'application/octet-stream', + }, + limited: false, + }, + ], + what: 'Fields and files' + }, + { source: [ + ['------WebKitFormBoundaryTB2MiQ36fnSJlrhY', + 'Content-Disposition: form-data; name="cont"', + '', + 'some random content', + '------WebKitFormBoundaryTB2MiQ36fnSJlrhY', + 'Content-Disposition: form-data; name="pass"', + '', + 'some random pass', + '------WebKitFormBoundaryTB2MiQ36fnSJlrhY', + 'Content-Disposition: form-data; name=bit', + '', + '2', + '------WebKitFormBoundaryTB2MiQ36fnSJlrhY--' + ].join('\r\n') + ], + boundary: '----WebKitFormBoundaryTB2MiQ36fnSJlrhY', + expected: [ + { type: 'field', + name: 'cont', + val: 'some random content', + info: { + nameTruncated: false, + valueTruncated: false, + encoding: '7bit', + mimeType: 'text/plain', + }, + }, + { type: 'field', + name: 'pass', + val: 'some random pass', + info: { + nameTruncated: false, + valueTruncated: false, + encoding: '7bit', + mimeType: 'text/plain', + }, + }, + { type: 'field', + name: 'bit', + val: '2', + info: { + nameTruncated: false, + valueTruncated: false, + encoding: '7bit', + mimeType: 'text/plain', + }, + }, + ], + what: 'Fields only' + }, + { source: [ + '' + ], + boundary: '----WebKitFormBoundaryTB2MiQ36fnSJlrhY', + expected: [ + { error: 'Unexpected end of form' }, + ], + what: 'No fields and no files' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; name="file_name_0"', + '', + 'super alpha file', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_0"; filename="1k_a.dat"', + 'Content-Type: application/octet-stream', + '', + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--' + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + limits: { + fileSize: 13, + fieldSize: 5 + }, + expected: [ + { type: 'field', + name: 'file_name_0', + val: 'super', + info: { + nameTruncated: false, + valueTruncated: true, + encoding: '7bit', + mimeType: 'text/plain', + }, + }, + { type: 'file', + name: 'upload_file_0', + data: Buffer.from('ABCDEFGHIJKLM'), + info: { + filename: '1k_a.dat', + encoding: '7bit', + mimeType: 'application/octet-stream', + }, + limited: true, + }, + ], + what: 'Fields and files (limits)' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; name="file_name_0"', + '', + 'super alpha file', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_0"; filename="1k_a.dat"', + 'Content-Type: application/octet-stream', + '', + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--' + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + limits: { + files: 0 + }, + expected: [ + { type: 'field', + name: 'file_name_0', + val: 'super alpha file', + info: { + nameTruncated: false, + valueTruncated: false, + encoding: '7bit', + mimeType: 'text/plain', + }, + }, + 'filesLimit', + ], + what: 'Fields and files (limits: 0 files)' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; name="file_name_0"', + '', + 'super alpha file', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; name="file_name_1"', + '', + 'super beta file', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_0"; filename="1k_a.dat"', + 'Content-Type: application/octet-stream', + '', + 'A'.repeat(1023), + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_1"; filename="1k_b.dat"', + 'Content-Type: application/octet-stream', + '', + 'B'.repeat(1023), + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--' + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + expected: [ + { type: 'field', + name: 'file_name_0', + val: 'super alpha file', + info: { + nameTruncated: false, + valueTruncated: false, + encoding: '7bit', + mimeType: 'text/plain', + }, + }, + { type: 'field', + name: 'file_name_1', + val: 'super beta file', + info: { + nameTruncated: false, + valueTruncated: false, + encoding: '7bit', + mimeType: 'text/plain', + }, + }, + ], + events: ['field'], + what: 'Fields and (ignored) files' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_0"; filename="/tmp/1k_a.dat"', + 'Content-Type: application/octet-stream', + '', + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_1"; filename="C:\\files\\1k_b.dat"', + 'Content-Type: application/octet-stream', + '', + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_2"; filename="relative/1k_c.dat"', + 'Content-Type: application/octet-stream', + '', + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--' + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + expected: [ + { type: 'file', + name: 'upload_file_0', + data: Buffer.from('ABCDEFGHIJKLMNOPQRSTUVWXYZ'), + info: { + filename: '1k_a.dat', + encoding: '7bit', + mimeType: 'application/octet-stream', + }, + limited: false, + }, + { type: 'file', + name: 'upload_file_1', + data: Buffer.from('ABCDEFGHIJKLMNOPQRSTUVWXYZ'), + info: { + filename: '1k_b.dat', + encoding: '7bit', + mimeType: 'application/octet-stream', + }, + limited: false, + }, + { type: 'file', + name: 'upload_file_2', + data: Buffer.from('ABCDEFGHIJKLMNOPQRSTUVWXYZ'), + info: { + filename: '1k_c.dat', + encoding: '7bit', + mimeType: 'application/octet-stream', + }, + limited: false, + }, + ], + what: 'Files with filenames containing paths' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_0"; filename="/absolute/1k_a.dat"', + 'Content-Type: application/octet-stream', + '', + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_1"; filename="C:\\absolute\\1k_b.dat"', + 'Content-Type: application/octet-stream', + '', + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_2"; filename="relative/1k_c.dat"', + 'Content-Type: application/octet-stream', + '', + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--' + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + preservePath: true, + expected: [ + { type: 'file', + name: 'upload_file_0', + data: Buffer.from('ABCDEFGHIJKLMNOPQRSTUVWXYZ'), + info: { + filename: '/absolute/1k_a.dat', + encoding: '7bit', + mimeType: 'application/octet-stream', + }, + limited: false, + }, + { type: 'file', + name: 'upload_file_1', + data: Buffer.from('ABCDEFGHIJKLMNOPQRSTUVWXYZ'), + info: { + filename: 'C:\\absolute\\1k_b.dat', + encoding: '7bit', + mimeType: 'application/octet-stream', + }, + limited: false, + }, + { type: 'file', + name: 'upload_file_2', + data: Buffer.from('ABCDEFGHIJKLMNOPQRSTUVWXYZ'), + info: { + filename: 'relative/1k_c.dat', + encoding: '7bit', + mimeType: 'application/octet-stream', + }, + limited: false, + }, + ], + what: 'Paths to be preserved through the preservePath option' + }, + { source: [ + ['------WebKitFormBoundaryTB2MiQ36fnSJlrhY', + 'Content-Disposition: form-data; name="cont"', + 'Content-Type: ', + '', + 'some random content', + '------WebKitFormBoundaryTB2MiQ36fnSJlrhY', + 'Content-Disposition: ', + '', + 'some random pass', + '------WebKitFormBoundaryTB2MiQ36fnSJlrhY--' + ].join('\r\n') + ], + boundary: '----WebKitFormBoundaryTB2MiQ36fnSJlrhY', + expected: [ + { type: 'field', + name: 'cont', + val: 'some random content', + info: { + nameTruncated: false, + valueTruncated: false, + encoding: '7bit', + mimeType: 'text/plain', + }, + }, + ], + what: 'Empty content-type and empty content-disposition' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="file"; filename*=utf-8\'\'n%C3%A4me.txt', + 'Content-Type: application/octet-stream', + '', + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--' + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + expected: [ + { type: 'file', + name: 'file', + data: Buffer.from('ABCDEFGHIJKLMNOPQRSTUVWXYZ'), + info: { + filename: 'näme.txt', + encoding: '7bit', + mimeType: 'application/octet-stream', + }, + limited: false, + }, + ], + what: 'Unicode filenames' + }, + { source: [ + ['--asdasdasdasd\r\n', + 'Content-Type: text/plain\r\n', + 'Content-Disposition: form-data; name="foo"\r\n', + '\r\n', + 'asd\r\n', + '--asdasdasdasd--' + ].join(':)') + ], + boundary: 'asdasdasdasd', + expected: [ + { error: 'Malformed part header' }, + { error: 'Unexpected end of form' }, + ], + what: 'Stopped mid-header' + }, + { source: [ + ['------WebKitFormBoundaryTB2MiQ36fnSJlrhY', + 'Content-Disposition: form-data; name="cont"', + 'Content-Type: application/json', + '', + '{}', + '------WebKitFormBoundaryTB2MiQ36fnSJlrhY--', + ].join('\r\n') + ], + boundary: '----WebKitFormBoundaryTB2MiQ36fnSJlrhY', + expected: [ + { type: 'field', + name: 'cont', + val: '{}', + info: { + nameTruncated: false, + valueTruncated: false, + encoding: '7bit', + mimeType: 'application/json', + }, + }, + ], + what: 'content-type for fields' + }, + { source: [ + '------WebKitFormBoundaryTB2MiQ36fnSJlrhY--', + ], + boundary: '----WebKitFormBoundaryTB2MiQ36fnSJlrhY', + expected: [], + what: 'empty form' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name=upload_file_0; filename="1k_a.dat"', + 'Content-Type: application/octet-stream', + 'Content-Transfer-Encoding: binary', + '', + '', + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + expected: [ + { type: 'file', + name: 'upload_file_0', + data: Buffer.alloc(0), + info: { + filename: '1k_a.dat', + encoding: 'binary', + mimeType: 'application/octet-stream', + }, + limited: false, + err: 'Unexpected end of form', + }, + { error: 'Unexpected end of form' }, + ], + what: 'Stopped mid-file #1' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name=upload_file_0; filename="1k_a.dat"', + 'Content-Type: application/octet-stream', + '', + 'a', + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + expected: [ + { type: 'file', + name: 'upload_file_0', + data: Buffer.from('a'), + info: { + filename: '1k_a.dat', + encoding: '7bit', + mimeType: 'application/octet-stream', + }, + limited: false, + err: 'Unexpected end of form', + }, + { error: 'Unexpected end of form' }, + ], + what: 'Stopped mid-file #2' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_0"; filename="notes.txt"', + 'Content-Type: text/plain; charset=utf8', + '', + 'a', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--', + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + expected: [ + { type: 'file', + name: 'upload_file_0', + data: Buffer.from('a'), + info: { + filename: 'notes.txt', + encoding: '7bit', + mimeType: 'text/plain', + }, + limited: false, + }, + ], + what: 'Text file with charset' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_0"; filename="notes.txt"', + 'Content-Type: ', + ' text/plain; charset=utf8', + '', + 'a', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--', + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + expected: [ + { type: 'file', + name: 'upload_file_0', + data: Buffer.from('a'), + info: { + filename: 'notes.txt', + encoding: '7bit', + mimeType: 'text/plain', + }, + limited: false, + }, + ], + what: 'Folded header value' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Type: text/plain; charset=utf8', + '', + 'a', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--', + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + expected: [], + what: 'No Content-Disposition' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; name="file_name_0"', + '', + 'a'.repeat(64 * 1024), + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_0"; filename="notes.txt"', + 'Content-Type: ', + ' text/plain; charset=utf8', + '', + 'bc', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--', + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + limits: { + fieldSize: Infinity, + }, + expected: [ + { type: 'file', + name: 'upload_file_0', + data: Buffer.from('bc'), + info: { + filename: 'notes.txt', + encoding: '7bit', + mimeType: 'text/plain', + }, + limited: false, + }, + ], + events: [ 'file' ], + what: 'Skip field parts if no listener' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; name="file_name_0"', + '', + 'a', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_0"; filename="notes.txt"', + 'Content-Type: ', + ' text/plain; charset=utf8', + '', + 'bc', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--', + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + limits: { + parts: 1, + }, + expected: [ + { type: 'field', + name: 'file_name_0', + val: 'a', + info: { + nameTruncated: false, + valueTruncated: false, + encoding: '7bit', + mimeType: 'text/plain', + }, + }, + 'partsLimit', + ], + what: 'Parts limit' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; name="file_name_0"', + '', + 'a', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; name="file_name_1"', + '', + 'b', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--', + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + limits: { + fields: 1, + }, + expected: [ + { type: 'field', + name: 'file_name_0', + val: 'a', + info: { + nameTruncated: false, + valueTruncated: false, + encoding: '7bit', + mimeType: 'text/plain', + }, + }, + 'fieldsLimit', + ], + what: 'Fields limit' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_0"; filename="notes.txt"', + 'Content-Type: text/plain; charset=utf8', + '', + 'ab', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_1"; filename="notes2.txt"', + 'Content-Type: text/plain; charset=utf8', + '', + 'cd', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--', + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + limits: { + files: 1, + }, + expected: [ + { type: 'file', + name: 'upload_file_0', + data: Buffer.from('ab'), + info: { + filename: 'notes.txt', + encoding: '7bit', + mimeType: 'text/plain', + }, + limited: false, + }, + 'filesLimit', + ], + what: 'Files limit' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + `name="upload_file_0"; filename="${'a'.repeat(64 * 1024)}.txt"`, + 'Content-Type: text/plain; charset=utf8', + '', + 'ab', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_1"; filename="notes2.txt"', + 'Content-Type: text/plain; charset=utf8', + '', + 'cd', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--', + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + expected: [ + { error: 'Malformed part header' }, + { type: 'file', + name: 'upload_file_1', + data: Buffer.from('cd'), + info: { + filename: 'notes2.txt', + encoding: '7bit', + mimeType: 'text/plain', + }, + limited: false, + }, + ], + what: 'Oversized part header' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_0"; filename="notes.txt"', + 'Content-Type: text/plain; charset=utf8', + '', + 'a'.repeat(31) + '\r', + ].join('\r\n'), + 'b'.repeat(40), + '\r\n-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--', + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + fileHwm: 32, + expected: [ + { type: 'file', + name: 'upload_file_0', + data: Buffer.from('a'.repeat(31) + '\r' + 'b'.repeat(40)), + info: { + filename: 'notes.txt', + encoding: '7bit', + mimeType: 'text/plain', + }, + limited: false, + }, + ], + what: 'Lookbehind data should not stall file streams' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + `name="upload_file_0"; filename="${'a'.repeat(8 * 1024)}.txt"`, + 'Content-Type: text/plain; charset=utf8', + '', + 'ab', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + `name="upload_file_1"; filename="${'b'.repeat(8 * 1024)}.txt"`, + 'Content-Type: text/plain; charset=utf8', + '', + 'cd', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + `name="upload_file_2"; filename="${'c'.repeat(8 * 1024)}.txt"`, + 'Content-Type: text/plain; charset=utf8', + '', + 'ef', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--', + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + expected: [ + { type: 'file', + name: 'upload_file_0', + data: Buffer.from('ab'), + info: { + filename: `${'a'.repeat(8 * 1024)}.txt`, + encoding: '7bit', + mimeType: 'text/plain', + }, + limited: false, + }, + { type: 'file', + name: 'upload_file_1', + data: Buffer.from('cd'), + info: { + filename: `${'b'.repeat(8 * 1024)}.txt`, + encoding: '7bit', + mimeType: 'text/plain', + }, + limited: false, + }, + { type: 'file', + name: 'upload_file_2', + data: Buffer.from('ef'), + info: { + filename: `${'c'.repeat(8 * 1024)}.txt`, + encoding: '7bit', + mimeType: 'text/plain', + }, + limited: false, + }, + ], + what: 'Header size limit should be per part' + }, + { source: [ + '\r\n--d1bf46b3-aa33-4061-b28d-6c5ced8b08ee\r\n', + 'Content-Type: application/gzip\r\n' + + 'Content-Encoding: gzip\r\n' + + 'Content-Disposition: form-data; name=batch-1; filename=batch-1' + + '\r\n\r\n', + '\r\n--d1bf46b3-aa33-4061-b28d-6c5ced8b08ee--', + ], + boundary: 'd1bf46b3-aa33-4061-b28d-6c5ced8b08ee', + expected: [ + { type: 'file', + name: 'batch-1', + data: Buffer.alloc(0), + info: { + filename: 'batch-1', + encoding: '7bit', + mimeType: 'application/gzip', + }, + limited: false, + }, + ], + what: 'Empty part' + }, +]; + +for (const test of tests) { + active.set(test, 1); + + const { what, boundary, events, limits, preservePath, fileHwm } = test; + const bb = busboy({ + fileHwm, + limits, + preservePath, + headers: { + 'content-type': `multipart/form-data; boundary=${boundary}`, + } + }); + const results = []; + + if (events === undefined || events.includes('field')) { + bb.on('field', (name, val, info) => { + results.push({ type: 'field', name, val, info }); + }); + } + + if (events === undefined || events.includes('file')) { + bb.on('file', (name, stream, info) => { + const data = []; + let nb = 0; + const file = { + type: 'file', + name, + data: null, + info, + limited: false, + }; + results.push(file); + stream.on('data', (d) => { + data.push(d); + nb += d.length; + }).on('limit', () => { + file.limited = true; + }).on('close', () => { + file.data = Buffer.concat(data, nb); + assert.strictEqual(stream.truncated, file.limited); + }).once('error', (err) => { + file.err = err.message; + }); + }); + } + + bb.on('error', (err) => { + results.push({ error: err.message }); + }); + + bb.on('partsLimit', () => { + results.push('partsLimit'); + }); + + bb.on('filesLimit', () => { + results.push('filesLimit'); + }); + + bb.on('fieldsLimit', () => { + results.push('fieldsLimit'); + }); + + bb.on('close', () => { + active.delete(test); + + assert.deepStrictEqual( + results, + test.expected, + `[${what}] Results mismatch.\n` + + `Parsed: ${inspect(results)}\n` + + `Expected: ${inspect(test.expected)}` + ); + }); + + for (const src of test.source) { + const buf = (typeof src === 'string' ? Buffer.from(src, 'utf8') : src); + bb.write(buf); + } + bb.end(); +} + +// Byte-by-byte versions +for (let test of tests) { + test = { ...test }; + test.what += ' (byte-by-byte)'; + active.set(test, 1); + + const { what, boundary, events, limits, preservePath, fileHwm } = test; + const bb = busboy({ + fileHwm, + limits, + preservePath, + headers: { + 'content-type': `multipart/form-data; boundary=${boundary}`, + } + }); + const results = []; + + if (events === undefined || events.includes('field')) { + bb.on('field', (name, val, info) => { + results.push({ type: 'field', name, val, info }); + }); + } + + if (events === undefined || events.includes('file')) { + bb.on('file', (name, stream, info) => { + const data = []; + let nb = 0; + const file = { + type: 'file', + name, + data: null, + info, + limited: false, + }; + results.push(file); + stream.on('data', (d) => { + data.push(d); + nb += d.length; + }).on('limit', () => { + file.limited = true; + }).on('close', () => { + file.data = Buffer.concat(data, nb); + assert.strictEqual(stream.truncated, file.limited); + }).once('error', (err) => { + file.err = err.message; + }); + }); + } + + bb.on('error', (err) => { + results.push({ error: err.message }); + }); + + bb.on('partsLimit', () => { + results.push('partsLimit'); + }); + + bb.on('filesLimit', () => { + results.push('filesLimit'); + }); + + bb.on('fieldsLimit', () => { + results.push('fieldsLimit'); + }); + + bb.on('close', () => { + active.delete(test); + + assert.deepStrictEqual( + results, + test.expected, + `[${what}] Results mismatch.\n` + + `Parsed: ${inspect(results)}\n` + + `Expected: ${inspect(test.expected)}` + ); + }); + + for (const src of test.source) { + const buf = (typeof src === 'string' ? Buffer.from(src, 'utf8') : src); + for (let i = 0; i < buf.length; ++i) + bb.write(buf.slice(i, i + 1)); + } + bb.end(); +} + +{ + let exception = false; + process.once('uncaughtException', (ex) => { + exception = true; + throw ex; + }); + process.on('exit', () => { + if (exception || active.size === 0) + return; + process.exitCode = 1; + console.error('=========================='); + console.error(`${active.size} test(s) did not finish:`); + console.error('=========================='); + console.error(Array.from(active.keys()).map((v) => v.what).join('\n')); + }); +} diff --git a/node_modules/busboy/test/test-types-urlencoded.js b/node_modules/busboy/test/test-types-urlencoded.js new file mode 100644 index 0000000..c35962b --- /dev/null +++ b/node_modules/busboy/test/test-types-urlencoded.js @@ -0,0 +1,488 @@ +'use strict'; + +const assert = require('assert'); +const { transcode } = require('buffer'); +const { inspect } = require('util'); + +const busboy = require('..'); + +const active = new Map(); + +const tests = [ + { source: ['foo'], + expected: [ + ['foo', + '', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Unassigned value' + }, + { source: ['foo=bar'], + expected: [ + ['foo', + 'bar', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Assigned value' + }, + { source: ['foo&bar=baz'], + expected: [ + ['foo', + '', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ['bar', + 'baz', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Unassigned and assigned value' + }, + { source: ['foo=bar&baz'], + expected: [ + ['foo', + 'bar', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ['baz', + '', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Assigned and unassigned value' + }, + { source: ['foo=bar&baz=bla'], + expected: [ + ['foo', + 'bar', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ['baz', + 'bla', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Two assigned values' + }, + { source: ['foo&bar'], + expected: [ + ['foo', + '', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ['bar', + '', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Two unassigned values' + }, + { source: ['foo&bar&'], + expected: [ + ['foo', + '', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ['bar', + '', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Two unassigned values and ampersand' + }, + { source: ['foo+1=bar+baz%2Bquux'], + expected: [ + ['foo 1', + 'bar baz+quux', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Assigned key and value with (plus) space' + }, + { source: ['foo=bar%20baz%21'], + expected: [ + ['foo', + 'bar baz!', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Assigned value with encoded bytes' + }, + { source: ['foo%20bar=baz%20bla%21'], + expected: [ + ['foo bar', + 'baz bla!', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Assigned value with encoded bytes #2' + }, + { source: ['foo=bar%20baz%21&num=1000'], + expected: [ + ['foo', + 'bar baz!', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ['num', + '1000', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Two assigned values, one with encoded bytes' + }, + { source: [ + Array.from(transcode(Buffer.from('foo'), 'utf8', 'utf16le')).map( + (n) => `%${n.toString(16).padStart(2, '0')}` + ).join(''), + '=', + Array.from(transcode(Buffer.from('😀!'), 'utf8', 'utf16le')).map( + (n) => `%${n.toString(16).padStart(2, '0')}` + ).join(''), + ], + expected: [ + ['foo', + '😀!', + { nameTruncated: false, + valueTruncated: false, + encoding: 'UTF-16LE', + mimeType: 'text/plain' }, + ], + ], + charset: 'UTF-16LE', + what: 'Encoded value with multi-byte charset' + }, + { source: [ + 'foo=<', + Array.from(transcode(Buffer.from('©:^þ'), 'utf8', 'latin1')).map( + (n) => `%${n.toString(16).padStart(2, '0')}` + ).join(''), + ], + expected: [ + ['foo', + '<©:^þ', + { nameTruncated: false, + valueTruncated: false, + encoding: 'ISO-8859-1', + mimeType: 'text/plain' }, + ], + ], + charset: 'ISO-8859-1', + what: 'Encoded value with single-byte, ASCII-compatible, non-UTF8 charset' + }, + { source: ['foo=bar&baz=bla'], + expected: [], + what: 'Limits: zero fields', + limits: { fields: 0 } + }, + { source: ['foo=bar&baz=bla'], + expected: [ + ['foo', + 'bar', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Limits: one field', + limits: { fields: 1 } + }, + { source: ['foo=bar&baz=bla'], + expected: [ + ['foo', + 'bar', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ['baz', + 'bla', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Limits: field part lengths match limits', + limits: { fieldNameSize: 3, fieldSize: 3 } + }, + { source: ['foo=bar&baz=bla'], + expected: [ + ['fo', + 'bar', + { nameTruncated: true, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ['ba', + 'bla', + { nameTruncated: true, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Limits: truncated field name', + limits: { fieldNameSize: 2 } + }, + { source: ['foo=bar&baz=bla'], + expected: [ + ['foo', + 'ba', + { nameTruncated: false, + valueTruncated: true, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ['baz', + 'bl', + { nameTruncated: false, + valueTruncated: true, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Limits: truncated field value', + limits: { fieldSize: 2 } + }, + { source: ['foo=bar&baz=bla'], + expected: [ + ['fo', + 'ba', + { nameTruncated: true, + valueTruncated: true, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ['ba', + 'bl', + { nameTruncated: true, + valueTruncated: true, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Limits: truncated field name and value', + limits: { fieldNameSize: 2, fieldSize: 2 } + }, + { source: ['foo=bar&baz=bla'], + expected: [ + ['fo', + '', + { nameTruncated: true, + valueTruncated: true, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ['ba', + '', + { nameTruncated: true, + valueTruncated: true, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Limits: truncated field name and zero value limit', + limits: { fieldNameSize: 2, fieldSize: 0 } + }, + { source: ['foo=bar&baz=bla'], + expected: [ + ['', + '', + { nameTruncated: true, + valueTruncated: true, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ['', + '', + { nameTruncated: true, + valueTruncated: true, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Limits: truncated zero field name and zero value limit', + limits: { fieldNameSize: 0, fieldSize: 0 } + }, + { source: ['&'], + expected: [], + what: 'Ampersand' + }, + { source: ['&&&&&'], + expected: [], + what: 'Many ampersands' + }, + { source: ['='], + expected: [ + ['', + '', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Assigned value, empty name and value' + }, + { source: [''], + expected: [], + what: 'Nothing' + }, +]; + +for (const test of tests) { + active.set(test, 1); + + const { what } = test; + const charset = test.charset || 'utf-8'; + const bb = busboy({ + limits: test.limits, + headers: { + 'content-type': `application/x-www-form-urlencoded; charset=${charset}`, + }, + }); + const results = []; + + bb.on('field', (key, val, info) => { + results.push([key, val, info]); + }); + + bb.on('file', () => { + throw new Error(`[${what}] Unexpected file`); + }); + + bb.on('close', () => { + active.delete(test); + + assert.deepStrictEqual( + results, + test.expected, + `[${what}] Results mismatch.\n` + + `Parsed: ${inspect(results)}\n` + + `Expected: ${inspect(test.expected)}` + ); + }); + + for (const src of test.source) { + const buf = (typeof src === 'string' ? Buffer.from(src, 'utf8') : src); + bb.write(buf); + } + bb.end(); +} + +// Byte-by-byte versions +for (let test of tests) { + test = { ...test }; + test.what += ' (byte-by-byte)'; + active.set(test, 1); + + const { what } = test; + const charset = test.charset || 'utf-8'; + const bb = busboy({ + limits: test.limits, + headers: { + 'content-type': `application/x-www-form-urlencoded; charset="${charset}"`, + }, + }); + const results = []; + + bb.on('field', (key, val, info) => { + results.push([key, val, info]); + }); + + bb.on('file', () => { + throw new Error(`[${what}] Unexpected file`); + }); + + bb.on('close', () => { + active.delete(test); + + assert.deepStrictEqual( + results, + test.expected, + `[${what}] Results mismatch.\n` + + `Parsed: ${inspect(results)}\n` + + `Expected: ${inspect(test.expected)}` + ); + }); + + for (const src of test.source) { + const buf = (typeof src === 'string' ? Buffer.from(src, 'utf8') : src); + for (let i = 0; i < buf.length; ++i) + bb.write(buf.slice(i, i + 1)); + } + bb.end(); +} + +{ + let exception = false; + process.once('uncaughtException', (ex) => { + exception = true; + throw ex; + }); + process.on('exit', () => { + if (exception || active.size === 0) + return; + process.exitCode = 1; + console.error('=========================='); + console.error(`${active.size} test(s) did not finish:`); + console.error('=========================='); + console.error(Array.from(active.keys()).map((v) => v.what).join('\n')); + }); +} diff --git a/node_modules/busboy/test/test.js b/node_modules/busboy/test/test.js new file mode 100644 index 0000000..d0380f2 --- /dev/null +++ b/node_modules/busboy/test/test.js @@ -0,0 +1,20 @@ +'use strict'; + +const { spawnSync } = require('child_process'); +const { readdirSync } = require('fs'); +const { join } = require('path'); + +const files = readdirSync(__dirname).sort(); +for (const filename of files) { + if (filename.startsWith('test-')) { + const path = join(__dirname, filename); + console.log(`> Running ${filename} ...`); + const result = spawnSync(`${process.argv0} ${path}`, { + shell: true, + stdio: 'inherit', + windowsHide: true + }); + if (result.status !== 0) + process.exitCode = 1; + } +} diff --git a/node_modules/bytes/History.md b/node_modules/bytes/History.md new file mode 100644 index 0000000..d60ce0e --- /dev/null +++ b/node_modules/bytes/History.md @@ -0,0 +1,97 @@ +3.1.2 / 2022-01-27 +================== + + * Fix return value for un-parsable strings + +3.1.1 / 2021-11-15 +================== + + * Fix "thousandsSeparator" incorrecting formatting fractional part + +3.1.0 / 2019-01-22 +================== + + * Add petabyte (`pb`) support + +3.0.0 / 2017-08-31 +================== + + * Change "kB" to "KB" in format output + * Remove support for Node.js 0.6 + * Remove support for ComponentJS + +2.5.0 / 2017-03-24 +================== + + * Add option "unit" + +2.4.0 / 2016-06-01 +================== + + * Add option "unitSeparator" + +2.3.0 / 2016-02-15 +================== + + * Drop partial bytes on all parsed units + * Fix non-finite numbers to `.format` to return `null` + * Fix parsing byte string that looks like hex + * perf: hoist regular expressions + +2.2.0 / 2015-11-13 +================== + + * add option "decimalPlaces" + * add option "fixedDecimals" + +2.1.0 / 2015-05-21 +================== + + * add `.format` export + * add `.parse` export + +2.0.2 / 2015-05-20 +================== + + * remove map recreation + * remove unnecessary object construction + +2.0.1 / 2015-05-07 +================== + + * fix browserify require + * remove node.extend dependency + +2.0.0 / 2015-04-12 +================== + + * add option "case" + * add option "thousandsSeparator" + * return "null" on invalid parse input + * support proper round-trip: bytes(bytes(num)) === num + * units no longer case sensitive when parsing + +1.0.0 / 2014-05-05 +================== + + * add negative support. fixes #6 + +0.3.0 / 2014-03-19 +================== + + * added terabyte support + +0.2.1 / 2013-04-01 +================== + + * add .component + +0.2.0 / 2012-10-28 +================== + + * bytes(200).should.eql('200b') + +0.1.0 / 2012-07-04 +================== + + * add bytes to string conversion [yields] diff --git a/node_modules/bytes/LICENSE b/node_modules/bytes/LICENSE new file mode 100644 index 0000000..63e95a9 --- /dev/null +++ b/node_modules/bytes/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2012-2014 TJ Holowaychuk +Copyright (c) 2015 Jed Watson + +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. diff --git a/node_modules/bytes/Readme.md b/node_modules/bytes/Readme.md new file mode 100644 index 0000000..5790e23 --- /dev/null +++ b/node_modules/bytes/Readme.md @@ -0,0 +1,152 @@ +# Bytes utility + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Utility to parse a string bytes (ex: `1TB`) to bytes (`1099511627776`) and vice-versa. + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```bash +$ npm install bytes +``` + +## Usage + +```js +var bytes = require('bytes'); +``` + +#### bytes(number|string value, [options]): number|string|null + +Default export function. Delegates to either `bytes.format` or `bytes.parse` based on the type of `value`. + +**Arguments** + +| Name | Type | Description | +|---------|----------|--------------------| +| value | `number`|`string` | Number value to format or string value to parse | +| options | `Object` | Conversion options for `format` | + +**Returns** + +| Name | Type | Description | +|---------|------------------|-------------------------------------------------| +| results | `string`|`number`|`null` | Return null upon error. Numeric value in bytes, or string value otherwise. | + +**Example** + +```js +bytes(1024); +// output: '1KB' + +bytes('1KB'); +// output: 1024 +``` + +#### bytes.format(number value, [options]): string|null + +Format the given value in bytes into a string. If the value is negative, it is kept as such. If it is a float, it is + rounded. + +**Arguments** + +| Name | Type | Description | +|---------|----------|--------------------| +| value | `number` | Value in bytes | +| options | `Object` | Conversion options | + +**Options** + +| Property | Type | Description | +|-------------------|--------|-----------------------------------------------------------------------------------------| +| decimalPlaces | `number`|`null` | Maximum number of decimal places to include in output. Default value to `2`. | +| fixedDecimals | `boolean`|`null` | Whether to always display the maximum number of decimal places. Default value to `false` | +| thousandsSeparator | `string`|`null` | Example of values: `' '`, `','` and `'.'`... Default value to `''`. | +| unit | `string`|`null` | The unit in which the result will be returned (B/KB/MB/GB/TB). Default value to `''` (which means auto detect). | +| unitSeparator | `string`|`null` | Separator to use between number and unit. Default value to `''`. | + +**Returns** + +| Name | Type | Description | +|---------|------------------|-------------------------------------------------| +| results | `string`|`null` | Return null upon error. String value otherwise. | + +**Example** + +```js +bytes.format(1024); +// output: '1KB' + +bytes.format(1000); +// output: '1000B' + +bytes.format(1000, {thousandsSeparator: ' '}); +// output: '1 000B' + +bytes.format(1024 * 1.7, {decimalPlaces: 0}); +// output: '2KB' + +bytes.format(1024, {unitSeparator: ' '}); +// output: '1 KB' +``` + +#### bytes.parse(string|number value): number|null + +Parse the string value into an integer in bytes. If no unit is given, or `value` +is a number, it is assumed the value is in bytes. + +Supported units and abbreviations are as follows and are case-insensitive: + + * `b` for bytes + * `kb` for kilobytes + * `mb` for megabytes + * `gb` for gigabytes + * `tb` for terabytes + * `pb` for petabytes + +The units are in powers of two, not ten. This means 1kb = 1024b according to this parser. + +**Arguments** + +| Name | Type | Description | +|---------------|--------|--------------------| +| value | `string`|`number` | String to parse, or number in bytes. | + +**Returns** + +| Name | Type | Description | +|---------|-------------|-------------------------| +| results | `number`|`null` | Return null upon error. Value in bytes otherwise. | + +**Example** + +```js +bytes.parse('1KB'); +// output: 1024 + +bytes.parse('1024'); +// output: 1024 + +bytes.parse(1024); +// output: 1024 +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/visionmedia/bytes.js/master?label=ci +[ci-url]: https://github.com/visionmedia/bytes.js/actions?query=workflow%3Aci +[coveralls-image]: https://badgen.net/coveralls/c/github/visionmedia/bytes.js/master +[coveralls-url]: https://coveralls.io/r/visionmedia/bytes.js?branch=master +[downloads-image]: https://badgen.net/npm/dm/bytes +[downloads-url]: https://npmjs.org/package/bytes +[npm-image]: https://badgen.net/npm/v/bytes +[npm-url]: https://npmjs.org/package/bytes diff --git a/node_modules/bytes/index.js b/node_modules/bytes/index.js new file mode 100644 index 0000000..6f2d0f8 --- /dev/null +++ b/node_modules/bytes/index.js @@ -0,0 +1,170 @@ +/*! + * bytes + * Copyright(c) 2012-2014 TJ Holowaychuk + * Copyright(c) 2015 Jed Watson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = bytes; +module.exports.format = format; +module.exports.parse = parse; + +/** + * Module variables. + * @private + */ + +var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; + +var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/; + +var map = { + b: 1, + kb: 1 << 10, + mb: 1 << 20, + gb: 1 << 30, + tb: Math.pow(1024, 4), + pb: Math.pow(1024, 5), +}; + +var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i; + +/** + * Convert the given value in bytes into a string or parse to string to an integer in bytes. + * + * @param {string|number} value + * @param {{ + * case: [string], + * decimalPlaces: [number] + * fixedDecimals: [boolean] + * thousandsSeparator: [string] + * unitSeparator: [string] + * }} [options] bytes options. + * + * @returns {string|number|null} + */ + +function bytes(value, options) { + if (typeof value === 'string') { + return parse(value); + } + + if (typeof value === 'number') { + return format(value, options); + } + + return null; +} + +/** + * Format the given value in bytes into a string. + * + * If the value is negative, it is kept as such. If it is a float, + * it is rounded. + * + * @param {number} value + * @param {object} [options] + * @param {number} [options.decimalPlaces=2] + * @param {number} [options.fixedDecimals=false] + * @param {string} [options.thousandsSeparator=] + * @param {string} [options.unit=] + * @param {string} [options.unitSeparator=] + * + * @returns {string|null} + * @public + */ + +function format(value, options) { + if (!Number.isFinite(value)) { + return null; + } + + var mag = Math.abs(value); + var thousandsSeparator = (options && options.thousandsSeparator) || ''; + var unitSeparator = (options && options.unitSeparator) || ''; + var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2; + var fixedDecimals = Boolean(options && options.fixedDecimals); + var unit = (options && options.unit) || ''; + + if (!unit || !map[unit.toLowerCase()]) { + if (mag >= map.pb) { + unit = 'PB'; + } else if (mag >= map.tb) { + unit = 'TB'; + } else if (mag >= map.gb) { + unit = 'GB'; + } else if (mag >= map.mb) { + unit = 'MB'; + } else if (mag >= map.kb) { + unit = 'KB'; + } else { + unit = 'B'; + } + } + + var val = value / map[unit.toLowerCase()]; + var str = val.toFixed(decimalPlaces); + + if (!fixedDecimals) { + str = str.replace(formatDecimalsRegExp, '$1'); + } + + if (thousandsSeparator) { + str = str.split('.').map(function (s, i) { + return i === 0 + ? s.replace(formatThousandsRegExp, thousandsSeparator) + : s + }).join('.'); + } + + return str + unitSeparator + unit; +} + +/** + * Parse the string value into an integer in bytes. + * + * If no unit is given, it is assumed the value is in bytes. + * + * @param {number|string} val + * + * @returns {number|null} + * @public + */ + +function parse(val) { + if (typeof val === 'number' && !isNaN(val)) { + return val; + } + + if (typeof val !== 'string') { + return null; + } + + // Test if the string passed is valid + var results = parseRegExp.exec(val); + var floatValue; + var unit = 'b'; + + if (!results) { + // Nothing could be extracted from the given string + floatValue = parseInt(val, 10); + unit = 'b' + } else { + // Retrieve the value and the unit + floatValue = parseFloat(results[1]); + unit = results[4].toLowerCase(); + } + + if (isNaN(floatValue)) { + return null; + } + + return Math.floor(map[unit] * floatValue); +} diff --git a/node_modules/bytes/package.json b/node_modules/bytes/package.json new file mode 100644 index 0000000..f2b6a8b --- /dev/null +++ b/node_modules/bytes/package.json @@ -0,0 +1,42 @@ +{ + "name": "bytes", + "description": "Utility to parse a string bytes to bytes and vice-versa", + "version": "3.1.2", + "author": "TJ Holowaychuk (http://tjholowaychuk.com)", + "contributors": [ + "Jed Watson ", + "Théo FIDRY " + ], + "license": "MIT", + "keywords": [ + "byte", + "bytes", + "utility", + "parse", + "parser", + "convert", + "converter" + ], + "repository": "visionmedia/bytes.js", + "devDependencies": { + "eslint": "7.32.0", + "eslint-plugin-markdown": "2.2.1", + "mocha": "9.2.0", + "nyc": "15.1.0" + }, + "files": [ + "History.md", + "LICENSE", + "Readme.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --check-leaks --reporter spec", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/node_modules/call-bind-apply-helpers/.eslintrc b/node_modules/call-bind-apply-helpers/.eslintrc new file mode 100644 index 0000000..201e859 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/.eslintrc @@ -0,0 +1,17 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "func-name-matching": 0, + "id-length": 0, + "new-cap": [2, { + "capIsNewExceptions": [ + "GetIntrinsic", + ], + }], + "no-extra-parens": 0, + "no-magic-numbers": 0, + }, +} diff --git a/node_modules/call-bind-apply-helpers/.github/FUNDING.yml b/node_modules/call-bind-apply-helpers/.github/FUNDING.yml new file mode 100644 index 0000000..0011e9d --- /dev/null +++ b/node_modules/call-bind-apply-helpers/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/call-bind-apply-helpers +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/call-bind-apply-helpers/.nycrc b/node_modules/call-bind-apply-helpers/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/call-bind-apply-helpers/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/call-bind-apply-helpers/CHANGELOG.md b/node_modules/call-bind-apply-helpers/CHANGELOG.md new file mode 100644 index 0000000..2484942 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/CHANGELOG.md @@ -0,0 +1,30 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.2](https://github.com/ljharb/call-bind-apply-helpers/compare/v1.0.1...v1.0.2) - 2025-02-12 + +### Commits + +- [types] improve inferred types [`e6f9586`](https://github.com/ljharb/call-bind-apply-helpers/commit/e6f95860a3c72879cb861a858cdfb8138fbedec1) +- [Dev Deps] update `@arethetypeswrong/cli`, `@ljharb/tsconfig`, `@types/tape`, `es-value-fixtures`, `for-each`, `has-strict-mode`, `object-inspect` [`e43d540`](https://github.com/ljharb/call-bind-apply-helpers/commit/e43d5409f97543bfbb11f345d47d8ce4e066d8c1) + +## [v1.0.1](https://github.com/ljharb/call-bind-apply-helpers/compare/v1.0.0...v1.0.1) - 2024-12-08 + +### Commits + +- [types] `reflectApply`: fix types [`4efc396`](https://github.com/ljharb/call-bind-apply-helpers/commit/4efc3965351a4f02cc55e836fa391d3d11ef2ef8) +- [Fix] `reflectApply`: oops, Reflect is not a function [`83cc739`](https://github.com/ljharb/call-bind-apply-helpers/commit/83cc7395de6b79b7730bdf092f1436f0b1263c75) +- [Dev Deps] update `@arethetypeswrong/cli` [`80bd5d3`](https://github.com/ljharb/call-bind-apply-helpers/commit/80bd5d3ae58b4f6b6995ce439dd5a1bcb178a940) + +## v1.0.0 - 2024-12-05 + +### Commits + +- Initial implementation, tests, readme [`7879629`](https://github.com/ljharb/call-bind-apply-helpers/commit/78796290f9b7430c9934d6f33d94ae9bc89fce04) +- Initial commit [`3f1dc16`](https://github.com/ljharb/call-bind-apply-helpers/commit/3f1dc164afc43285631b114a5f9dd9137b2b952f) +- npm init [`081df04`](https://github.com/ljharb/call-bind-apply-helpers/commit/081df048c312fcee400922026f6e97281200a603) +- Only apps should have lockfiles [`5b9ca0f`](https://github.com/ljharb/call-bind-apply-helpers/commit/5b9ca0fe8101ebfaf309c549caac4e0a017ed930) diff --git a/node_modules/call-bind-apply-helpers/LICENSE b/node_modules/call-bind-apply-helpers/LICENSE new file mode 100644 index 0000000..f82f389 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Jordan Harband + +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. diff --git a/node_modules/call-bind-apply-helpers/README.md b/node_modules/call-bind-apply-helpers/README.md new file mode 100644 index 0000000..8fc0dae --- /dev/null +++ b/node_modules/call-bind-apply-helpers/README.md @@ -0,0 +1,62 @@ +# call-bind-apply-helpers [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Helper functions around Function call/apply/bind, for use in `call-bind`. + +The only packages that should likely ever use this package directly are `call-bind` and `get-intrinsic`. +Please use `call-bind` unless you have a very good reason not to. + +## Getting started + +```sh +npm install --save call-bind-apply-helpers +``` + +## Usage/Examples + +```js +const assert = require('assert'); +const callBindBasic = require('call-bind-apply-helpers'); + +function f(a, b) { + assert.equal(this, 1); + assert.equal(a, 2); + assert.equal(b, 3); + assert.equal(arguments.length, 2); +} + +const fBound = callBindBasic([f, 1]); + +delete Function.prototype.call; +delete Function.prototype.bind; + +fBound(2, 3); +``` + +## Tests + +Clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/call-bind-apply-helpers +[npm-version-svg]: https://versionbadg.es/ljharb/call-bind-apply-helpers.svg +[deps-svg]: https://david-dm.org/ljharb/call-bind-apply-helpers.svg +[deps-url]: https://david-dm.org/ljharb/call-bind-apply-helpers +[dev-deps-svg]: https://david-dm.org/ljharb/call-bind-apply-helpers/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/call-bind-apply-helpers#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/call-bind-apply-helpers.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/call-bind-apply-helpers.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/call-bind-apply-helpers.svg +[downloads-url]: https://npm-stat.com/charts.html?package=call-bind-apply-helpers +[codecov-image]: https://codecov.io/gh/ljharb/call-bind-apply-helpers/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/call-bind-apply-helpers/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/call-bind-apply-helpers +[actions-url]: https://github.com/ljharb/call-bind-apply-helpers/actions diff --git a/node_modules/call-bind-apply-helpers/actualApply.d.ts b/node_modules/call-bind-apply-helpers/actualApply.d.ts new file mode 100644 index 0000000..b87286a --- /dev/null +++ b/node_modules/call-bind-apply-helpers/actualApply.d.ts @@ -0,0 +1 @@ +export = Reflect.apply; \ No newline at end of file diff --git a/node_modules/call-bind-apply-helpers/actualApply.js b/node_modules/call-bind-apply-helpers/actualApply.js new file mode 100644 index 0000000..ffa5135 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/actualApply.js @@ -0,0 +1,10 @@ +'use strict'; + +var bind = require('function-bind'); + +var $apply = require('./functionApply'); +var $call = require('./functionCall'); +var $reflectApply = require('./reflectApply'); + +/** @type {import('./actualApply')} */ +module.exports = $reflectApply || bind.call($call, $apply); diff --git a/node_modules/call-bind-apply-helpers/applyBind.d.ts b/node_modules/call-bind-apply-helpers/applyBind.d.ts new file mode 100644 index 0000000..d176c1a --- /dev/null +++ b/node_modules/call-bind-apply-helpers/applyBind.d.ts @@ -0,0 +1,19 @@ +import actualApply from './actualApply'; + +type TupleSplitHead = T['length'] extends N + ? T + : T extends [...infer R, any] + ? TupleSplitHead + : never + +type TupleSplitTail = O['length'] extends N + ? T + : T extends [infer F, ...infer R] + ? TupleSplitTail<[...R], N, [...O, F]> + : never + +type TupleSplit = [TupleSplitHead, TupleSplitTail] + +declare function applyBind(...args: TupleSplit, 2>[1]): ReturnType; + +export = applyBind; \ No newline at end of file diff --git a/node_modules/call-bind-apply-helpers/applyBind.js b/node_modules/call-bind-apply-helpers/applyBind.js new file mode 100644 index 0000000..d2b7723 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/applyBind.js @@ -0,0 +1,10 @@ +'use strict'; + +var bind = require('function-bind'); +var $apply = require('./functionApply'); +var actualApply = require('./actualApply'); + +/** @type {import('./applyBind')} */ +module.exports = function applyBind() { + return actualApply(bind, $apply, arguments); +}; diff --git a/node_modules/call-bind-apply-helpers/functionApply.d.ts b/node_modules/call-bind-apply-helpers/functionApply.d.ts new file mode 100644 index 0000000..1f6e11b --- /dev/null +++ b/node_modules/call-bind-apply-helpers/functionApply.d.ts @@ -0,0 +1 @@ +export = Function.prototype.apply; \ No newline at end of file diff --git a/node_modules/call-bind-apply-helpers/functionApply.js b/node_modules/call-bind-apply-helpers/functionApply.js new file mode 100644 index 0000000..c71df9c --- /dev/null +++ b/node_modules/call-bind-apply-helpers/functionApply.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./functionApply')} */ +module.exports = Function.prototype.apply; diff --git a/node_modules/call-bind-apply-helpers/functionCall.d.ts b/node_modules/call-bind-apply-helpers/functionCall.d.ts new file mode 100644 index 0000000..15e93df --- /dev/null +++ b/node_modules/call-bind-apply-helpers/functionCall.d.ts @@ -0,0 +1 @@ +export = Function.prototype.call; \ No newline at end of file diff --git a/node_modules/call-bind-apply-helpers/functionCall.js b/node_modules/call-bind-apply-helpers/functionCall.js new file mode 100644 index 0000000..7a8d873 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/functionCall.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./functionCall')} */ +module.exports = Function.prototype.call; diff --git a/node_modules/call-bind-apply-helpers/index.d.ts b/node_modules/call-bind-apply-helpers/index.d.ts new file mode 100644 index 0000000..541516b --- /dev/null +++ b/node_modules/call-bind-apply-helpers/index.d.ts @@ -0,0 +1,64 @@ +type RemoveFromTuple< + Tuple extends readonly unknown[], + RemoveCount extends number, + Index extends 1[] = [] +> = Index["length"] extends RemoveCount + ? Tuple + : Tuple extends [infer First, ...infer Rest] + ? RemoveFromTuple + : Tuple; + +type ConcatTuples< + Prefix extends readonly unknown[], + Suffix extends readonly unknown[] +> = [...Prefix, ...Suffix]; + +type ExtractFunctionParams = T extends (this: infer TThis, ...args: infer P extends readonly unknown[]) => infer R + ? { thisArg: TThis; params: P; returnType: R } + : never; + +type BindFunction< + T extends (this: any, ...args: any[]) => any, + TThis, + TBoundArgs extends readonly unknown[], + ReceiverBound extends boolean +> = ExtractFunctionParams extends { + thisArg: infer OrigThis; + params: infer P extends readonly unknown[]; + returnType: infer R; +} + ? ReceiverBound extends true + ? (...args: RemoveFromTuple>) => R extends [OrigThis, ...infer Rest] + ? [TThis, ...Rest] // Replace `this` with `thisArg` + : R + : >>( + thisArg: U, + ...args: RemainingArgs + ) => R extends [OrigThis, ...infer Rest] + ? [U, ...ConcatTuples] // Preserve bound args in return type + : R + : never; + +declare function callBind< + const T extends (this: any, ...args: any[]) => any, + Extracted extends ExtractFunctionParams, + const TBoundArgs extends Partial & readonly unknown[], + const TThis extends Extracted["thisArg"] +>( + args: [fn: T, thisArg: TThis, ...boundArgs: TBoundArgs] +): BindFunction; + +declare function callBind< + const T extends (this: any, ...args: any[]) => any, + Extracted extends ExtractFunctionParams, + const TBoundArgs extends Partial & readonly unknown[] +>( + args: [fn: T, ...boundArgs: TBoundArgs] +): BindFunction; + +declare function callBind( + args: [fn: Exclude, ...rest: TArgs] +): never; + +// export as namespace callBind; +export = callBind; diff --git a/node_modules/call-bind-apply-helpers/index.js b/node_modules/call-bind-apply-helpers/index.js new file mode 100644 index 0000000..2f6dab4 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/index.js @@ -0,0 +1,15 @@ +'use strict'; + +var bind = require('function-bind'); +var $TypeError = require('es-errors/type'); + +var $call = require('./functionCall'); +var $actualApply = require('./actualApply'); + +/** @type {(args: [Function, thisArg?: unknown, ...args: unknown[]]) => Function} TODO FIXME, find a way to use import('.') */ +module.exports = function callBindBasic(args) { + if (args.length < 1 || typeof args[0] !== 'function') { + throw new $TypeError('a function is required'); + } + return $actualApply(bind, $call, args); +}; diff --git a/node_modules/call-bind-apply-helpers/package.json b/node_modules/call-bind-apply-helpers/package.json new file mode 100644 index 0000000..923b8be --- /dev/null +++ b/node_modules/call-bind-apply-helpers/package.json @@ -0,0 +1,85 @@ +{ + "name": "call-bind-apply-helpers", + "version": "1.0.2", + "description": "Helper functions around Function call/apply/bind, for use in `call-bind`", + "main": "index.js", + "exports": { + ".": "./index.js", + "./actualApply": "./actualApply.js", + "./applyBind": "./applyBind.js", + "./functionApply": "./functionApply.js", + "./functionCall": "./functionCall.js", + "./reflectApply": "./reflectApply.js", + "./package.json": "./package.json" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=auto", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "prelint": "evalmd README.md", + "lint": "eslint --ext=.js,.mjs .", + "postlint": "tsc -p . && attw -P", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>=10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/call-bind-apply-helpers.git" + }, + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/call-bind-apply-helpers/issues" + }, + "homepage": "https://github.com/ljharb/call-bind-apply-helpers#readme", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.3", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.3", + "@types/for-each": "^0.3.3", + "@types/function-bind": "^1.1.10", + "@types/object-inspect": "^1.13.0", + "@types/tape": "^5.8.1", + "auto-changelog": "^2.5.0", + "encoding": "^0.1.13", + "es-value-fixtures": "^1.7.1", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.5", + "has-strict-mode": "^1.1.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "object-inspect": "^1.13.4", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "testling": { + "files": "test/index.js" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/call-bind-apply-helpers/reflectApply.d.ts b/node_modules/call-bind-apply-helpers/reflectApply.d.ts new file mode 100644 index 0000000..6b2ae76 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/reflectApply.d.ts @@ -0,0 +1,3 @@ +declare const reflectApply: false | typeof Reflect.apply; + +export = reflectApply; diff --git a/node_modules/call-bind-apply-helpers/reflectApply.js b/node_modules/call-bind-apply-helpers/reflectApply.js new file mode 100644 index 0000000..3d03caa --- /dev/null +++ b/node_modules/call-bind-apply-helpers/reflectApply.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./reflectApply')} */ +module.exports = typeof Reflect !== 'undefined' && Reflect && Reflect.apply; diff --git a/node_modules/call-bind-apply-helpers/test/index.js b/node_modules/call-bind-apply-helpers/test/index.js new file mode 100644 index 0000000..1cdc89e --- /dev/null +++ b/node_modules/call-bind-apply-helpers/test/index.js @@ -0,0 +1,63 @@ +'use strict'; + +var callBind = require('../'); +var hasStrictMode = require('has-strict-mode')(); +var forEach = require('for-each'); +var inspect = require('object-inspect'); +var v = require('es-value-fixtures'); + +var test = require('tape'); + +test('callBindBasic', function (t) { + forEach(v.nonFunctions, function (nonFunction) { + t['throws']( + // @ts-expect-error + function () { callBind([nonFunction]); }, + TypeError, + inspect(nonFunction) + ' is not a function' + ); + }); + + var sentinel = { sentinel: true }; + /** @type {(this: T, a: A, b: B) => [T | undefined, A, B]} */ + var func = function (a, b) { + // eslint-disable-next-line no-invalid-this + return [!hasStrictMode && this === global ? undefined : this, a, b]; + }; + t.equal(func.length, 2, 'original function length is 2'); + + /** type {(thisArg: unknown, a: number, b: number) => [unknown, number, number]} */ + var bound = callBind([func]); + /** type {((a: number, b: number) => [typeof sentinel, typeof a, typeof b])} */ + var boundR = callBind([func, sentinel]); + /** type {((b: number) => [typeof sentinel, number, typeof b])} */ + var boundArg = callBind([func, sentinel, /** @type {const} */ (1)]); + + // @ts-expect-error + t.deepEqual(bound(), [undefined, undefined, undefined], 'bound func with no args'); + + // @ts-expect-error + t.deepEqual(func(), [undefined, undefined, undefined], 'unbound func with too few args'); + // @ts-expect-error + t.deepEqual(bound(1, 2), [hasStrictMode ? 1 : Object(1), 2, undefined], 'bound func too few args'); + // @ts-expect-error + t.deepEqual(boundR(), [sentinel, undefined, undefined], 'bound func with receiver, with too few args'); + // @ts-expect-error + t.deepEqual(boundArg(), [sentinel, 1, undefined], 'bound func with receiver and arg, with too few args'); + + t.deepEqual(func(1, 2), [undefined, 1, 2], 'unbound func with right args'); + t.deepEqual(bound(1, 2, 3), [hasStrictMode ? 1 : Object(1), 2, 3], 'bound func with right args'); + t.deepEqual(boundR(1, 2), [sentinel, 1, 2], 'bound func with receiver, with right args'); + t.deepEqual(boundArg(2), [sentinel, 1, 2], 'bound func with receiver and arg, with right arg'); + + // @ts-expect-error + t.deepEqual(func(1, 2, 3), [undefined, 1, 2], 'unbound func with too many args'); + // @ts-expect-error + t.deepEqual(bound(1, 2, 3, 4), [hasStrictMode ? 1 : Object(1), 2, 3], 'bound func with too many args'); + // @ts-expect-error + t.deepEqual(boundR(1, 2, 3), [sentinel, 1, 2], 'bound func with receiver, with too many args'); + // @ts-expect-error + t.deepEqual(boundArg(2, 3), [sentinel, 1, 2], 'bound func with receiver and arg, with too many args'); + + t.end(); +}); diff --git a/node_modules/call-bind-apply-helpers/tsconfig.json b/node_modules/call-bind-apply-helpers/tsconfig.json new file mode 100644 index 0000000..aef9993 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "es2021", + }, + "exclude": [ + "coverage", + ], +} \ No newline at end of file diff --git a/node_modules/call-bound/.eslintrc b/node_modules/call-bound/.eslintrc new file mode 100644 index 0000000..2612ed8 --- /dev/null +++ b/node_modules/call-bound/.eslintrc @@ -0,0 +1,13 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "new-cap": [2, { + "capIsNewExceptions": [ + "GetIntrinsic", + ], + }], + }, +} diff --git a/node_modules/call-bound/.github/FUNDING.yml b/node_modules/call-bound/.github/FUNDING.yml new file mode 100644 index 0000000..2a2a135 --- /dev/null +++ b/node_modules/call-bound/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/call-bound +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/call-bound/.nycrc b/node_modules/call-bound/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/call-bound/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/call-bound/CHANGELOG.md b/node_modules/call-bound/CHANGELOG.md new file mode 100644 index 0000000..8bde4e9 --- /dev/null +++ b/node_modules/call-bound/CHANGELOG.md @@ -0,0 +1,42 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.4](https://github.com/ljharb/call-bound/compare/v1.0.3...v1.0.4) - 2025-03-03 + +### Commits + +- [types] improve types [`e648922`](https://github.com/ljharb/call-bound/commit/e6489222a9e54f350fbf952ceabe51fd8b6027ff) +- [Dev Deps] update `@arethetypeswrong/cli`, `@ljharb/tsconfig`, `@types/tape`, `es-value-fixtures`, `for-each`, `has-strict-mode`, `object-inspect` [`a42a5eb`](https://github.com/ljharb/call-bound/commit/a42a5ebe6c1b54fcdc7997c7dc64fdca9e936719) +- [Deps] update `call-bind-apply-helpers`, `get-intrinsic` [`f529eac`](https://github.com/ljharb/call-bound/commit/f529eac132404c17156bbc23ab2297a25d0f20b8) + +## [v1.0.3](https://github.com/ljharb/call-bound/compare/v1.0.2...v1.0.3) - 2024-12-15 + +### Commits + +- [Refactor] use `call-bind-apply-helpers` instead of `call-bind` [`5e0b134`](https://github.com/ljharb/call-bound/commit/5e0b13496df14fb7d05dae9412f088da8d3f75be) +- [Deps] update `get-intrinsic` [`41fc967`](https://github.com/ljharb/call-bound/commit/41fc96732a22c7b7e8f381f93ccc54bb6293be2e) +- [readme] fix example [`79a0137`](https://github.com/ljharb/call-bound/commit/79a0137723f7c6d09c9c05452bbf8d5efb5d6e49) +- [meta] add `sideEffects` flag [`08b07be`](https://github.com/ljharb/call-bound/commit/08b07be7f1c03f67dc6f3cdaf0906259771859f7) + +## [v1.0.2](https://github.com/ljharb/call-bound/compare/v1.0.1...v1.0.2) - 2024-12-10 + +### Commits + +- [Dev Deps] update `@arethetypeswrong/cli`, `@ljharb/tsconfig`, `gopd` [`e6a5ffe`](https://github.com/ljharb/call-bound/commit/e6a5ffe849368fe4f74dfd6cdeca1b9baa39e8d5) +- [Deps] update `call-bind`, `get-intrinsic` [`2aeb5b5`](https://github.com/ljharb/call-bound/commit/2aeb5b521dc2b2683d1345c753ea1161de2d1c14) +- [types] improve return type [`1a0c9fe`](https://github.com/ljharb/call-bound/commit/1a0c9fe3114471e7ca1f57d104e2efe713bb4871) + +## v1.0.1 - 2024-12-05 + +### Commits + +- Initial implementation, tests, readme, types [`6d94121`](https://github.com/ljharb/call-bound/commit/6d94121a9243602e506334069f7a03189fe3363d) +- Initial commit [`0eae867`](https://github.com/ljharb/call-bound/commit/0eae867334ea025c33e6e91cdecfc9df96680cf9) +- npm init [`71b2479`](https://github.com/ljharb/call-bound/commit/71b2479c6723e0b7d91a6b663613067e98b7b275) +- Only apps should have lockfiles [`c3754a9`](https://github.com/ljharb/call-bound/commit/c3754a949b7f9132b47e2d18c1729889736741eb) +- [actions] skip `npm ls` in node < 10 [`74275a5`](https://github.com/ljharb/call-bound/commit/74275a5186b8caf6309b6b97472bdcb0df4683a8) +- [Dev Deps] add missing peer dep [`1354de8`](https://github.com/ljharb/call-bound/commit/1354de8679413e4ae9c523d85f76fa7a5e032d97) diff --git a/node_modules/call-bound/LICENSE b/node_modules/call-bound/LICENSE new file mode 100644 index 0000000..f82f389 --- /dev/null +++ b/node_modules/call-bound/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Jordan Harband + +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. diff --git a/node_modules/call-bound/README.md b/node_modules/call-bound/README.md new file mode 100644 index 0000000..a44e43e --- /dev/null +++ b/node_modules/call-bound/README.md @@ -0,0 +1,53 @@ +# call-bound [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Robust call-bound JavaScript intrinsics, using `call-bind` and `get-intrinsic`. + +## Getting started + +```sh +npm install --save call-bound +``` + +## Usage/Examples + +```js +const assert = require('assert'); +const callBound = require('call-bound'); + +const slice = callBound('Array.prototype.slice'); + +delete Function.prototype.call; +delete Function.prototype.bind; +delete Array.prototype.slice; + +assert.deepEqual(slice([1, 2, 3, 4], 1, -1), [2, 3]); +``` + +## Tests + +Clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/call-bound +[npm-version-svg]: https://versionbadg.es/ljharb/call-bound.svg +[deps-svg]: https://david-dm.org/ljharb/call-bound.svg +[deps-url]: https://david-dm.org/ljharb/call-bound +[dev-deps-svg]: https://david-dm.org/ljharb/call-bound/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/call-bound#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/call-bound.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/call-bound.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/call-bound.svg +[downloads-url]: https://npm-stat.com/charts.html?package=call-bound +[codecov-image]: https://codecov.io/gh/ljharb/call-bound/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/call-bound/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/call-bound +[actions-url]: https://github.com/ljharb/call-bound/actions diff --git a/node_modules/call-bound/index.d.ts b/node_modules/call-bound/index.d.ts new file mode 100644 index 0000000..5562f00 --- /dev/null +++ b/node_modules/call-bound/index.d.ts @@ -0,0 +1,94 @@ +type Intrinsic = typeof globalThis; + +type IntrinsicName = keyof Intrinsic | `%${keyof Intrinsic}%`; + +type IntrinsicPath = IntrinsicName | `${StripPercents}.${string}` | `%${StripPercents}.${string}%`; + +type AllowMissing = boolean; + +type StripPercents = T extends `%${infer U}%` ? U : T; + +type BindMethodPrecise = + F extends (this: infer This, ...args: infer Args) => infer R + ? (obj: This, ...args: Args) => R + : F extends { + (this: infer This1, ...args: infer Args1): infer R1; + (this: infer This2, ...args: infer Args2): infer R2 + } + ? { + (obj: This1, ...args: Args1): R1; + (obj: This2, ...args: Args2): R2 + } + : never + +// Extract method type from a prototype +type GetPrototypeMethod = + (typeof globalThis)[T] extends { prototype: any } + ? M extends keyof (typeof globalThis)[T]['prototype'] + ? (typeof globalThis)[T]['prototype'][M] + : never + : never + +// Get static property/method +type GetStaticMember = + P extends keyof (typeof globalThis)[T] ? (typeof globalThis)[T][P] : never + +// Type that maps string path to actual bound function or value with better precision +type BoundIntrinsic = + S extends `${infer Obj}.prototype.${infer Method}` + ? Obj extends keyof typeof globalThis + ? BindMethodPrecise> + : unknown + : S extends `${infer Obj}.${infer Prop}` + ? Obj extends keyof typeof globalThis + ? GetStaticMember + : unknown + : unknown + +declare function arraySlice(array: readonly T[], start?: number, end?: number): T[]; +declare function arraySlice(array: ArrayLike, start?: number, end?: number): T[]; +declare function arraySlice(array: IArguments, start?: number, end?: number): T[]; + +// Special cases for methods that need explicit typing +interface SpecialCases { + '%Object.prototype.isPrototypeOf%': (thisArg: {}, obj: unknown) => boolean; + '%String.prototype.replace%': { + (str: string, searchValue: string | RegExp, replaceValue: string): string; + (str: string, searchValue: string | RegExp, replacer: (substring: string, ...args: any[]) => string): string + }; + '%Object.prototype.toString%': (obj: {}) => string; + '%Object.prototype.hasOwnProperty%': (obj: {}, v: PropertyKey) => boolean; + '%Array.prototype.slice%': typeof arraySlice; + '%Array.prototype.map%': (array: readonly T[], callbackfn: (value: T, index: number, array: readonly T[]) => U, thisArg?: any) => U[]; + '%Array.prototype.filter%': (array: readonly T[], predicate: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any) => T[]; + '%Array.prototype.indexOf%': (array: readonly T[], searchElement: T, fromIndex?: number) => number; + '%Function.prototype.apply%': (fn: (...args: A) => R, thisArg: any, args: A) => R; + '%Function.prototype.call%': (fn: (...args: A) => R, thisArg: any, ...args: A) => R; + '%Function.prototype.bind%': (fn: (...args: A) => R, thisArg: any, ...args: A) => (...remainingArgs: A) => R; + '%Promise.prototype.then%': { + (promise: Promise, onfulfilled: (value: T) => R | PromiseLike): Promise; + (promise: Promise, onfulfilled: ((value: T) => R | PromiseLike) | undefined | null, onrejected: (reason: any) => R | PromiseLike): Promise; + }; + '%RegExp.prototype.test%': (regexp: RegExp, str: string) => boolean; + '%RegExp.prototype.exec%': (regexp: RegExp, str: string) => RegExpExecArray | null; + '%Error.prototype.toString%': (error: Error) => string; + '%TypeError.prototype.toString%': (error: TypeError) => string; + '%String.prototype.split%': ( + obj: unknown, + splitter: string | RegExp | { + [Symbol.split](string: string, limit?: number): string[]; + }, + limit?: number | undefined + ) => string[]; +} + +/** + * Returns a bound function for a prototype method, or a value for a static property. + * + * @param name - The name of the intrinsic (e.g. 'Array.prototype.slice') + * @param {AllowMissing} [allowMissing] - Whether to allow missing intrinsics (default: false) + */ +declare function callBound, S extends IntrinsicPath>(name: K, allowMissing?: AllowMissing): SpecialCases[`%${StripPercents}%`]; +declare function callBound, S extends IntrinsicPath>(name: S, allowMissing?: AllowMissing): BoundIntrinsic; + +export = callBound; diff --git a/node_modules/call-bound/index.js b/node_modules/call-bound/index.js new file mode 100644 index 0000000..e9ade74 --- /dev/null +++ b/node_modules/call-bound/index.js @@ -0,0 +1,19 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); + +var callBindBasic = require('call-bind-apply-helpers'); + +/** @type {(thisArg: string, searchString: string, position?: number) => number} */ +var $indexOf = callBindBasic([GetIntrinsic('%String.prototype.indexOf%')]); + +/** @type {import('.')} */ +module.exports = function callBoundIntrinsic(name, allowMissing) { + /* eslint no-extra-parens: 0 */ + + var intrinsic = /** @type {(this: unknown, ...args: unknown[]) => unknown} */ (GetIntrinsic(name, !!allowMissing)); + if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { + return callBindBasic(/** @type {const} */ ([intrinsic])); + } + return intrinsic; +}; diff --git a/node_modules/call-bound/package.json b/node_modules/call-bound/package.json new file mode 100644 index 0000000..d542db4 --- /dev/null +++ b/node_modules/call-bound/package.json @@ -0,0 +1,99 @@ +{ + "name": "call-bound", + "version": "1.0.4", + "description": "Robust call-bound JavaScript intrinsics, using `call-bind` and `get-intrinsic`.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=auto", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "prelint": "evalmd README.md", + "lint": "eslint --ext=.js,.mjs .", + "postlint": "tsc -p . && attw -P", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>=10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/call-bound.git" + }, + "keywords": [ + "javascript", + "ecmascript", + "es", + "js", + "callbind", + "callbound", + "call", + "bind", + "bound", + "call-bind", + "call-bound", + "function", + "es-abstract" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/call-bound/issues" + }, + "homepage": "https://github.com/ljharb/call-bound#readme", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.4", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.3.0", + "@types/call-bind": "^1.0.5", + "@types/get-intrinsic": "^1.2.3", + "@types/tape": "^5.8.1", + "auto-changelog": "^2.5.0", + "encoding": "^0.1.13", + "es-value-fixtures": "^1.7.1", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.5", + "gopd": "^1.2.0", + "has-strict-mode": "^1.1.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "object-inspect": "^1.13.4", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "testling": { + "files": "test/index.js" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/call-bound/test/index.js b/node_modules/call-bound/test/index.js new file mode 100644 index 0000000..a2fc9f0 --- /dev/null +++ b/node_modules/call-bound/test/index.js @@ -0,0 +1,61 @@ +'use strict'; + +var test = require('tape'); + +var callBound = require('../'); + +/** @template {true} T @template U @typedef {T extends U ? T : never} AssertType */ + +test('callBound', function (t) { + // static primitive + t.equal(callBound('Array.length'), Array.length, 'Array.length yields itself'); + t.equal(callBound('%Array.length%'), Array.length, '%Array.length% yields itself'); + + // static non-function object + t.equal(callBound('Array.prototype'), Array.prototype, 'Array.prototype yields itself'); + t.equal(callBound('%Array.prototype%'), Array.prototype, '%Array.prototype% yields itself'); + t.equal(callBound('Array.constructor'), Array.constructor, 'Array.constructor yields itself'); + t.equal(callBound('%Array.constructor%'), Array.constructor, '%Array.constructor% yields itself'); + + // static function + t.equal(callBound('Date.parse'), Date.parse, 'Date.parse yields itself'); + t.equal(callBound('%Date.parse%'), Date.parse, '%Date.parse% yields itself'); + + // prototype primitive + t.equal(callBound('Error.prototype.message'), Error.prototype.message, 'Error.prototype.message yields itself'); + t.equal(callBound('%Error.prototype.message%'), Error.prototype.message, '%Error.prototype.message% yields itself'); + + var x = callBound('Object.prototype.toString'); + var y = callBound('%Object.prototype.toString%'); + + // prototype function + t.notEqual(x, Object.prototype.toString, 'Object.prototype.toString does not yield itself'); + t.notEqual(y, Object.prototype.toString, '%Object.prototype.toString% does not yield itself'); + t.equal(x(true), Object.prototype.toString.call(true), 'call-bound Object.prototype.toString calls into the original'); + t.equal(y(true), Object.prototype.toString.call(true), 'call-bound %Object.prototype.toString% calls into the original'); + + t['throws']( + // @ts-expect-error + function () { callBound('does not exist'); }, + SyntaxError, + 'nonexistent intrinsic throws' + ); + t['throws']( + // @ts-expect-error + function () { callBound('does not exist', true); }, + SyntaxError, + 'allowMissing arg still throws for unknown intrinsic' + ); + + t.test('real but absent intrinsic', { skip: typeof WeakRef !== 'undefined' }, function (st) { + st['throws']( + function () { callBound('WeakRef'); }, + TypeError, + 'real but absent intrinsic throws' + ); + st.equal(callBound('WeakRef', true), undefined, 'allowMissing arg avoids exception'); + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/call-bound/tsconfig.json b/node_modules/call-bound/tsconfig.json new file mode 100644 index 0000000..8976d98 --- /dev/null +++ b/node_modules/call-bound/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "ESNext", + "lib": ["es2024"], + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/combined-stream/License b/node_modules/combined-stream/License new file mode 100644 index 0000000..4804b7a --- /dev/null +++ b/node_modules/combined-stream/License @@ -0,0 +1,19 @@ +Copyright (c) 2011 Debuggable Limited + +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. diff --git a/node_modules/combined-stream/Readme.md b/node_modules/combined-stream/Readme.md new file mode 100644 index 0000000..9e367b5 --- /dev/null +++ b/node_modules/combined-stream/Readme.md @@ -0,0 +1,138 @@ +# combined-stream + +A stream that emits multiple other streams one after another. + +**NB** Currently `combined-stream` works with streams version 1 only. There is ongoing effort to switch this library to streams version 2. Any help is welcome. :) Meanwhile you can explore other libraries that provide streams2 support with more or less compatibility with `combined-stream`. + +- [combined-stream2](https://www.npmjs.com/package/combined-stream2): A drop-in streams2-compatible replacement for the combined-stream module. + +- [multistream](https://www.npmjs.com/package/multistream): A stream that emits multiple other streams one after another. + +## Installation + +``` bash +npm install combined-stream +``` + +## Usage + +Here is a simple example that shows how you can use combined-stream to combine +two files into one: + +``` javascript +var CombinedStream = require('combined-stream'); +var fs = require('fs'); + +var combinedStream = CombinedStream.create(); +combinedStream.append(fs.createReadStream('file1.txt')); +combinedStream.append(fs.createReadStream('file2.txt')); + +combinedStream.pipe(fs.createWriteStream('combined.txt')); +``` + +While the example above works great, it will pause all source streams until +they are needed. If you don't want that to happen, you can set `pauseStreams` +to `false`: + +``` javascript +var CombinedStream = require('combined-stream'); +var fs = require('fs'); + +var combinedStream = CombinedStream.create({pauseStreams: false}); +combinedStream.append(fs.createReadStream('file1.txt')); +combinedStream.append(fs.createReadStream('file2.txt')); + +combinedStream.pipe(fs.createWriteStream('combined.txt')); +``` + +However, what if you don't have all the source streams yet, or you don't want +to allocate the resources (file descriptors, memory, etc.) for them right away? +Well, in that case you can simply provide a callback that supplies the stream +by calling a `next()` function: + +``` javascript +var CombinedStream = require('combined-stream'); +var fs = require('fs'); + +var combinedStream = CombinedStream.create(); +combinedStream.append(function(next) { + next(fs.createReadStream('file1.txt')); +}); +combinedStream.append(function(next) { + next(fs.createReadStream('file2.txt')); +}); + +combinedStream.pipe(fs.createWriteStream('combined.txt')); +``` + +## API + +### CombinedStream.create([options]) + +Returns a new combined stream object. Available options are: + +* `maxDataSize` +* `pauseStreams` + +The effect of those options is described below. + +### combinedStream.pauseStreams = `true` + +Whether to apply back pressure to the underlaying streams. If set to `false`, +the underlaying streams will never be paused. If set to `true`, the +underlaying streams will be paused right after being appended, as well as when +`delayedStream.pipe()` wants to throttle. + +### combinedStream.maxDataSize = `2 * 1024 * 1024` + +The maximum amount of bytes (or characters) to buffer for all source streams. +If this value is exceeded, `combinedStream` emits an `'error'` event. + +### combinedStream.dataSize = `0` + +The amount of bytes (or characters) currently buffered by `combinedStream`. + +### combinedStream.append(stream) + +Appends the given `stream` to the combinedStream object. If `pauseStreams` is +set to `true, this stream will also be paused right away. + +`streams` can also be a function that takes one parameter called `next`. `next` +is a function that must be invoked in order to provide the `next` stream, see +example above. + +Regardless of how the `stream` is appended, combined-stream always attaches an +`'error'` listener to it, so you don't have to do that manually. + +Special case: `stream` can also be a String or Buffer. + +### combinedStream.write(data) + +You should not call this, `combinedStream` takes care of piping the appended +streams into itself for you. + +### combinedStream.resume() + +Causes `combinedStream` to start drain the streams it manages. The function is +idempotent, and also emits a `'resume'` event each time which usually goes to +the stream that is currently being drained. + +### combinedStream.pause(); + +If `combinedStream.pauseStreams` is set to `false`, this does nothing. +Otherwise a `'pause'` event is emitted, this goes to the stream that is +currently being drained, so you can use it to apply back pressure. + +### combinedStream.end(); + +Sets `combinedStream.writable` to false, emits an `'end'` event, and removes +all streams from the queue. + +### combinedStream.destroy(); + +Same as `combinedStream.end()`, except it emits a `'close'` event instead of +`'end'`. + +## License + +combined-stream is licensed under the MIT license. diff --git a/node_modules/combined-stream/lib/combined_stream.js b/node_modules/combined-stream/lib/combined_stream.js new file mode 100644 index 0000000..125f097 --- /dev/null +++ b/node_modules/combined-stream/lib/combined_stream.js @@ -0,0 +1,208 @@ +var util = require('util'); +var Stream = require('stream').Stream; +var DelayedStream = require('delayed-stream'); + +module.exports = CombinedStream; +function CombinedStream() { + this.writable = false; + this.readable = true; + this.dataSize = 0; + this.maxDataSize = 2 * 1024 * 1024; + this.pauseStreams = true; + + this._released = false; + this._streams = []; + this._currentStream = null; + this._insideLoop = false; + this._pendingNext = false; +} +util.inherits(CombinedStream, Stream); + +CombinedStream.create = function(options) { + var combinedStream = new this(); + + options = options || {}; + for (var option in options) { + combinedStream[option] = options[option]; + } + + return combinedStream; +}; + +CombinedStream.isStreamLike = function(stream) { + return (typeof stream !== 'function') + && (typeof stream !== 'string') + && (typeof stream !== 'boolean') + && (typeof stream !== 'number') + && (!Buffer.isBuffer(stream)); +}; + +CombinedStream.prototype.append = function(stream) { + var isStreamLike = CombinedStream.isStreamLike(stream); + + if (isStreamLike) { + if (!(stream instanceof DelayedStream)) { + var newStream = DelayedStream.create(stream, { + maxDataSize: Infinity, + pauseStream: this.pauseStreams, + }); + stream.on('data', this._checkDataSize.bind(this)); + stream = newStream; + } + + this._handleErrors(stream); + + if (this.pauseStreams) { + stream.pause(); + } + } + + this._streams.push(stream); + return this; +}; + +CombinedStream.prototype.pipe = function(dest, options) { + Stream.prototype.pipe.call(this, dest, options); + this.resume(); + return dest; +}; + +CombinedStream.prototype._getNext = function() { + this._currentStream = null; + + if (this._insideLoop) { + this._pendingNext = true; + return; // defer call + } + + this._insideLoop = true; + try { + do { + this._pendingNext = false; + this._realGetNext(); + } while (this._pendingNext); + } finally { + this._insideLoop = false; + } +}; + +CombinedStream.prototype._realGetNext = function() { + var stream = this._streams.shift(); + + + if (typeof stream == 'undefined') { + this.end(); + return; + } + + if (typeof stream !== 'function') { + this._pipeNext(stream); + return; + } + + var getStream = stream; + getStream(function(stream) { + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on('data', this._checkDataSize.bind(this)); + this._handleErrors(stream); + } + + this._pipeNext(stream); + }.bind(this)); +}; + +CombinedStream.prototype._pipeNext = function(stream) { + this._currentStream = stream; + + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on('end', this._getNext.bind(this)); + stream.pipe(this, {end: false}); + return; + } + + var value = stream; + this.write(value); + this._getNext(); +}; + +CombinedStream.prototype._handleErrors = function(stream) { + var self = this; + stream.on('error', function(err) { + self._emitError(err); + }); +}; + +CombinedStream.prototype.write = function(data) { + this.emit('data', data); +}; + +CombinedStream.prototype.pause = function() { + if (!this.pauseStreams) { + return; + } + + if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause(); + this.emit('pause'); +}; + +CombinedStream.prototype.resume = function() { + if (!this._released) { + this._released = true; + this.writable = true; + this._getNext(); + } + + if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume(); + this.emit('resume'); +}; + +CombinedStream.prototype.end = function() { + this._reset(); + this.emit('end'); +}; + +CombinedStream.prototype.destroy = function() { + this._reset(); + this.emit('close'); +}; + +CombinedStream.prototype._reset = function() { + this.writable = false; + this._streams = []; + this._currentStream = null; +}; + +CombinedStream.prototype._checkDataSize = function() { + this._updateDataSize(); + if (this.dataSize <= this.maxDataSize) { + return; + } + + var message = + 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'; + this._emitError(new Error(message)); +}; + +CombinedStream.prototype._updateDataSize = function() { + this.dataSize = 0; + + var self = this; + this._streams.forEach(function(stream) { + if (!stream.dataSize) { + return; + } + + self.dataSize += stream.dataSize; + }); + + if (this._currentStream && this._currentStream.dataSize) { + this.dataSize += this._currentStream.dataSize; + } +}; + +CombinedStream.prototype._emitError = function(err) { + this._reset(); + this.emit('error', err); +}; diff --git a/node_modules/combined-stream/package.json b/node_modules/combined-stream/package.json new file mode 100644 index 0000000..6982b6d --- /dev/null +++ b/node_modules/combined-stream/package.json @@ -0,0 +1,25 @@ +{ + "author": "Felix Geisendörfer (http://debuggable.com/)", + "name": "combined-stream", + "description": "A stream that emits multiple other streams one after another.", + "version": "1.0.8", + "homepage": "https://github.com/felixge/node-combined-stream", + "repository": { + "type": "git", + "url": "git://github.com/felixge/node-combined-stream.git" + }, + "main": "./lib/combined_stream", + "scripts": { + "test": "node test/run.js" + }, + "engines": { + "node": ">= 0.8" + }, + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "devDependencies": { + "far": "~0.0.7" + }, + "license": "MIT" +} diff --git a/node_modules/combined-stream/yarn.lock b/node_modules/combined-stream/yarn.lock new file mode 100644 index 0000000..7edf418 --- /dev/null +++ b/node_modules/combined-stream/yarn.lock @@ -0,0 +1,17 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + +delayed-stream@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619" + +far@~0.0.7: + version "0.0.7" + resolved "https://registry.yarnpkg.com/far/-/far-0.0.7.tgz#01c1fd362bcd26ce9cf161af3938aa34619f79a7" + dependencies: + oop "0.0.3" + +oop@0.0.3: + version "0.0.3" + resolved "https://registry.yarnpkg.com/oop/-/oop-0.0.3.tgz#70fa405a5650891a194fdc82ca68dad6dabf4401" diff --git a/node_modules/concat-stream/LICENSE b/node_modules/concat-stream/LICENSE new file mode 100644 index 0000000..99c130e --- /dev/null +++ b/node_modules/concat-stream/LICENSE @@ -0,0 +1,24 @@ +The MIT License + +Copyright (c) 2013 Max Ogden + +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. \ No newline at end of file diff --git a/node_modules/concat-stream/index.js b/node_modules/concat-stream/index.js new file mode 100644 index 0000000..dd672a7 --- /dev/null +++ b/node_modules/concat-stream/index.js @@ -0,0 +1,144 @@ +var Writable = require('readable-stream').Writable +var inherits = require('inherits') +var bufferFrom = require('buffer-from') + +if (typeof Uint8Array === 'undefined') { + var U8 = require('typedarray').Uint8Array +} else { + var U8 = Uint8Array +} + +function ConcatStream(opts, cb) { + if (!(this instanceof ConcatStream)) return new ConcatStream(opts, cb) + + if (typeof opts === 'function') { + cb = opts + opts = {} + } + if (!opts) opts = {} + + var encoding = opts.encoding + var shouldInferEncoding = false + + if (!encoding) { + shouldInferEncoding = true + } else { + encoding = String(encoding).toLowerCase() + if (encoding === 'u8' || encoding === 'uint8') { + encoding = 'uint8array' + } + } + + Writable.call(this, { objectMode: true }) + + this.encoding = encoding + this.shouldInferEncoding = shouldInferEncoding + + if (cb) this.on('finish', function () { cb(this.getBody()) }) + this.body = [] +} + +module.exports = ConcatStream +inherits(ConcatStream, Writable) + +ConcatStream.prototype._write = function(chunk, enc, next) { + this.body.push(chunk) + next() +} + +ConcatStream.prototype.inferEncoding = function (buff) { + var firstBuffer = buff === undefined ? this.body[0] : buff; + if (Buffer.isBuffer(firstBuffer)) return 'buffer' + if (typeof Uint8Array !== 'undefined' && firstBuffer instanceof Uint8Array) return 'uint8array' + if (Array.isArray(firstBuffer)) return 'array' + if (typeof firstBuffer === 'string') return 'string' + if (Object.prototype.toString.call(firstBuffer) === "[object Object]") return 'object' + return 'buffer' +} + +ConcatStream.prototype.getBody = function () { + if (!this.encoding && this.body.length === 0) return [] + if (this.shouldInferEncoding) this.encoding = this.inferEncoding() + if (this.encoding === 'array') return arrayConcat(this.body) + if (this.encoding === 'string') return stringConcat(this.body) + if (this.encoding === 'buffer') return bufferConcat(this.body) + if (this.encoding === 'uint8array') return u8Concat(this.body) + return this.body +} + +var isArray = Array.isArray || function (arr) { + return Object.prototype.toString.call(arr) == '[object Array]' +} + +function isArrayish (arr) { + return /Array\]$/.test(Object.prototype.toString.call(arr)) +} + +function isBufferish (p) { + return typeof p === 'string' || isArrayish(p) || (p && typeof p.subarray === 'function') +} + +function stringConcat (parts) { + var strings = [] + var needsToString = false + for (var i = 0; i < parts.length; i++) { + var p = parts[i] + if (typeof p === 'string') { + strings.push(p) + } else if (Buffer.isBuffer(p)) { + strings.push(p) + } else if (isBufferish(p)) { + strings.push(bufferFrom(p)) + } else { + strings.push(bufferFrom(String(p))) + } + } + if (Buffer.isBuffer(parts[0])) { + strings = Buffer.concat(strings) + strings = strings.toString('utf8') + } else { + strings = strings.join('') + } + return strings +} + +function bufferConcat (parts) { + var bufs = [] + for (var i = 0; i < parts.length; i++) { + var p = parts[i] + if (Buffer.isBuffer(p)) { + bufs.push(p) + } else if (isBufferish(p)) { + bufs.push(bufferFrom(p)) + } else { + bufs.push(bufferFrom(String(p))) + } + } + return Buffer.concat(bufs) +} + +function arrayConcat (parts) { + var res = [] + for (var i = 0; i < parts.length; i++) { + res.push.apply(res, parts[i]) + } + return res +} + +function u8Concat (parts) { + var len = 0 + for (var i = 0; i < parts.length; i++) { + if (typeof parts[i] === 'string') { + parts[i] = bufferFrom(parts[i]) + } + len += parts[i].length + } + var u8 = new U8(len) + for (var i = 0, offset = 0; i < parts.length; i++) { + var part = parts[i] + for (var j = 0; j < part.length; j++) { + u8[offset++] = part[j] + } + } + return u8 +} diff --git a/node_modules/concat-stream/package.json b/node_modules/concat-stream/package.json new file mode 100644 index 0000000..3797828 --- /dev/null +++ b/node_modules/concat-stream/package.json @@ -0,0 +1,55 @@ +{ + "name": "concat-stream", + "version": "2.0.0", + "description": "writable stream that concatenates strings or binary data and calls a callback with the result", + "tags": [ + "stream", + "simple", + "util", + "utility" + ], + "author": "Max Ogden ", + "repository": { + "type": "git", + "url": "http://github.com/maxogden/concat-stream.git" + }, + "bugs": { + "url": "http://github.com/maxogden/concat-stream/issues" + }, + "engines": [ + "node >= 6.0" + ], + "main": "index.js", + "files": [ + "index.js" + ], + "scripts": { + "test": "tape test/*.js test/server/*.js" + }, + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.0.2", + "typedarray": "^0.0.6" + }, + "devDependencies": { + "tape": "^4.6.3" + }, + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/8..latest", + "firefox/17..latest", + "firefox/nightly", + "chrome/22..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + } +} diff --git a/node_modules/concat-stream/readme.md b/node_modules/concat-stream/readme.md new file mode 100644 index 0000000..7aa19c4 --- /dev/null +++ b/node_modules/concat-stream/readme.md @@ -0,0 +1,102 @@ +# concat-stream + +Writable stream that concatenates all the data from a stream and calls a callback with the result. Use this when you want to collect all the data from a stream into a single buffer. + +[![Build Status](https://travis-ci.org/maxogden/concat-stream.svg?branch=master)](https://travis-ci.org/maxogden/concat-stream) + +[![NPM](https://nodei.co/npm/concat-stream.png)](https://nodei.co/npm/concat-stream/) + +### description + +Streams emit many buffers. If you want to collect all of the buffers, and when the stream ends concatenate all of the buffers together and receive a single buffer then this is the module for you. + +Only use this if you know you can fit all of the output of your stream into a single Buffer (e.g. in RAM). + +There are also `objectMode` streams that emit things other than Buffers, and you can concatenate these too. See below for details. + +## Related + +`concat-stream` is part of the [mississippi stream utility collection](https://github.com/maxogden/mississippi) which includes more useful stream modules similar to this one. + +### examples + +#### Buffers + +```js +var fs = require('fs') +var concat = require('concat-stream') + +var readStream = fs.createReadStream('cat.png') +var concatStream = concat(gotPicture) + +readStream.on('error', handleError) +readStream.pipe(concatStream) + +function gotPicture(imageBuffer) { + // imageBuffer is all of `cat.png` as a node.js Buffer +} + +function handleError(err) { + // handle your error appropriately here, e.g.: + console.error(err) // print the error to STDERR + process.exit(1) // exit program with non-zero exit code +} + +``` + +#### Arrays + +```js +var write = concat(function(data) {}) +write.write([1,2,3]) +write.write([4,5,6]) +write.end() +// data will be [1,2,3,4,5,6] in the above callback +``` + +#### Uint8Arrays + +```js +var write = concat(function(data) {}) +var a = new Uint8Array(3) +a[0] = 97; a[1] = 98; a[2] = 99 +write.write(a) +write.write('!') +write.end(Buffer.from('!!1')) +``` + +See `test/` for more examples + +# methods + +```js +var concat = require('concat-stream') +``` + +## var writable = concat(opts={}, cb) + +Return a `writable` stream that will fire `cb(data)` with all of the data that +was written to the stream. Data can be written to `writable` as strings, +Buffers, arrays of byte integers, and Uint8Arrays. + +By default `concat-stream` will give you back the same data type as the type of the first buffer written to the stream. Use `opts.encoding` to set what format `data` should be returned as, e.g. if you if you don't want to rely on the built-in type checking or for some other reason. + +* `string` - get a string +* `buffer` - get back a Buffer +* `array` - get an array of byte integers +* `uint8array`, `u8`, `uint8` - get back a Uint8Array +* `object`, get back an array of Objects + +If you don't specify an encoding, and the types can't be inferred (e.g. you write things that aren't in the list above), it will try to convert concat them into a `Buffer`. + +If nothing is written to `writable` then `data` will be an empty array `[]`. + +# error handling + +`concat-stream` does not handle errors for you, so you must handle errors on whatever streams you pipe into `concat-stream`. This is a general rule when programming with node.js streams: always handle errors on each and every stream. Since `concat-stream` is not itself a stream it does not emit errors. + +We recommend using [`end-of-stream`](https://npmjs.org/end-of-stream) or [`pump`](https://npmjs.org/pump) for writing error tolerant stream code. + +# license + +MIT LICENSE diff --git a/node_modules/content-disposition/LICENSE b/node_modules/content-disposition/LICENSE new file mode 100644 index 0000000..84441fb --- /dev/null +++ b/node_modules/content-disposition/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2017 Douglas Christopher Wilson + +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. diff --git a/node_modules/content-disposition/README.md b/node_modules/content-disposition/README.md new file mode 100644 index 0000000..75c91a9 --- /dev/null +++ b/node_modules/content-disposition/README.md @@ -0,0 +1,141 @@ +# content-disposition + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][github-actions-ci-image]][github-actions-ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Create and parse HTTP `Content-Disposition` header + +## Installation + +```sh +$ npm install content-disposition +``` + +## API + +```js +const contentDisposition = require('content-disposition') +``` + +### contentDisposition(filename, options) + +Create an attachment `Content-Disposition` header value using the given file name, +if supplied. The `filename` is optional and if no file name is desired, but you +want to specify `options`, set `filename` to `undefined`. + +```js +res.setHeader('Content-Disposition', contentDisposition('∫ maths.pdf')) +``` + +**note** HTTP headers are of the ISO-8859-1 character set. If you are writing this +header through a means different from `setHeader` in Node.js, you'll want to specify +the `'binary'` encoding in Node.js. + +#### Options + +`contentDisposition` accepts these properties in the options object. + +##### fallback + +If the `filename` option is outside ISO-8859-1, then the file name is actually +stored in a supplemental field for clients that support Unicode file names and +a ISO-8859-1 version of the file name is automatically generated. + +This specifies the ISO-8859-1 file name to override the automatic generation or +disables the generation all together, defaults to `true`. + + - A string will specify the ISO-8859-1 file name to use in place of automatic + generation. + - `false` will disable including a ISO-8859-1 file name and only include the + Unicode version (unless the file name is already ISO-8859-1). + - `true` will enable automatic generation if the file name is outside ISO-8859-1. + +If the `filename` option is ISO-8859-1 and this option is specified and has a +different value, then the `filename` option is encoded in the extended field +and this set as the fallback field, even though they are both ISO-8859-1. + +##### type + +Specifies the disposition type, defaults to `"attachment"`. This can also be +`"inline"`, or any other value (all values except inline are treated like +`attachment`, but can convey additional information if both parties agree to +it). The type is normalized to lower-case. + +### contentDisposition.parse(string) + +```js +const disposition = contentDisposition.parse('attachment; filename="EURO rates.txt"; filename*=UTF-8\'\'%e2%82%ac%20rates.txt') +``` + +Parse a `Content-Disposition` header string. This automatically handles extended +("Unicode") parameters by decoding them and providing them under the standard +parameter name. This will return an object with the following properties (examples +are shown for the string `'attachment; filename="EURO rates.txt"; filename*=UTF-8\'\'%e2%82%ac%20rates.txt'`): + + - `type`: The disposition type (always lower case). Example: `'attachment'` + + - `parameters`: An object of the parameters in the disposition (name of parameter + always lower case and extended versions replace non-extended versions). Example: + `{filename: "€ rates.txt"}` + +## Examples + +### Send a file for download + +```js +const contentDisposition = require('content-disposition') +const fs = require('fs') +const http = require('http') +const onFinished = require('on-finished') + +const filePath = '/path/to/public/plans.pdf' + +http.createServer(function onRequest (req, res) { + // set headers + res.setHeader('Content-Type', 'application/pdf') + res.setHeader('Content-Disposition', contentDisposition(filePath)) + + // send file + const stream = fs.createReadStream(filePath) + stream.pipe(res) + onFinished(res, function () { + stream.destroy() + }) +}) +``` + +## Testing + +```sh +$ npm test +``` + +## References + +- [RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1][rfc-2616] +- [RFC 5987: Character Set and Language Encoding for Hypertext Transfer Protocol (HTTP) Header Field Parameters][rfc-5987] +- [RFC 6266: Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)][rfc-6266] +- [Test Cases for HTTP Content-Disposition header field (RFC 6266) and the Encodings defined in RFCs 2047, 2231 and 5987][tc-2231] + +[rfc-2616]: https://datatracker.ietf.org/doc/html/rfc2616 +[rfc-5987]: https://datatracker.ietf.org/doc/html/rfc5987 +[rfc-6266]: https://datatracker.ietf.org/doc/html/rfc6266 +[tc-2231]: http://greenbytes.de/tech/tc2231/ + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/content-disposition +[npm-url]: https://www.npmjs.com/package/content-disposition +[node-version-image]: https://img.shields.io/node/v/content-disposition +[node-version-url]: https://nodejs.org/en/download +[coveralls-image]: https://img.shields.io/coverallsCoverage/github/jshttp/content-disposition +[coveralls-url]: https://coveralls.io/github/jshttp/content-disposition?branch=master +[downloads-image]: https://img.shields.io/npm/dm/content-disposition +[downloads-url]: https://www.npmjs.com/package/content-disposition +[github-actions-ci-image]: https://img.shields.io/github/actions/workflow/status/jshttp/content-disposition/ci.yml +[github-actions-ci-url]: https://github.com/jshttp/content-disposition/actions/workflows/ci.yml diff --git a/node_modules/content-disposition/index.js b/node_modules/content-disposition/index.js new file mode 100644 index 0000000..d1e313a --- /dev/null +++ b/node_modules/content-disposition/index.js @@ -0,0 +1,536 @@ +/*! + * content-disposition + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = contentDisposition +module.exports.parse = parse + +/** + * TextDecoder instance for UTF-8 decoding when decodeURIComponent fails due to invalid byte sequences. + * @type {TextDecoder} + * @private + */ +const utf8Decoder = new TextDecoder('utf-8') + +/** + * RegExp to match non attr-char, *after* encodeURIComponent (i.e. not including "%") + * @private + */ + +var ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g // eslint-disable-line no-control-regex + +/** + * RegExp to match non-latin1 characters. + * @private + */ + +var NON_LATIN1_REGEXP = /[^\x20-\x7e\xa0-\xff]/g + +/** + * RegExp to match quoted-pair in RFC 2616 + * + * quoted-pair = "\" CHAR + * CHAR = + * @private + */ + +var QESC_REGEXP = /\\([\u0000-\u007f])/g // eslint-disable-line no-control-regex + +/** + * RegExp to match chars that must be quoted-pair in RFC 2616 + * @private + */ + +var QUOTE_REGEXP = /([\\"])/g + +/** + * RegExp for various RFC 2616 grammar + * + * parameter = token "=" ( token | quoted-string ) + * token = 1* + * separators = "(" | ")" | "<" | ">" | "@" + * | "," | ";" | ":" | "\" | <"> + * | "/" | "[" | "]" | "?" | "=" + * | "{" | "}" | SP | HT + * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) + * qdtext = > + * quoted-pair = "\" CHAR + * CHAR = + * TEXT = + * LWS = [CRLF] 1*( SP | HT ) + * CRLF = CR LF + * CR = + * LF = + * SP = + * HT = + * CTL = + * OCTET = + * @private + */ + +var PARAM_REGEXP = /;[\x09\x20]*([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*=[\x09\x20]*("(?:[\x20!\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*/g // eslint-disable-line no-control-regex +var TEXT_REGEXP = /^[\x20-\x7e\x80-\xff]+$/ +var TOKEN_REGEXP = /^[!#$%&'*+.0-9A-Z^_`a-z|~-]+$/ + +/** + * RegExp for various RFC 5987 grammar + * + * ext-value = charset "'" [ language ] "'" value-chars + * charset = "UTF-8" / "ISO-8859-1" / mime-charset + * mime-charset = 1*mime-charsetc + * mime-charsetc = ALPHA / DIGIT + * / "!" / "#" / "$" / "%" / "&" + * / "+" / "-" / "^" / "_" / "`" + * / "{" / "}" / "~" + * language = ( 2*3ALPHA [ extlang ] ) + * / 4ALPHA + * / 5*8ALPHA + * extlang = *3( "-" 3ALPHA ) + * value-chars = *( pct-encoded / attr-char ) + * pct-encoded = "%" HEXDIG HEXDIG + * attr-char = ALPHA / DIGIT + * / "!" / "#" / "$" / "&" / "+" / "-" / "." + * / "^" / "_" / "`" / "|" / "~" + * @private + */ + +var EXT_VALUE_REGEXP = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+.^_`|~-])+)$/ + +/** + * RegExp for various RFC 6266 grammar + * + * disposition-type = "inline" | "attachment" | disp-ext-type + * disp-ext-type = token + * disposition-parm = filename-parm | disp-ext-parm + * filename-parm = "filename" "=" value + * | "filename*" "=" ext-value + * disp-ext-parm = token "=" value + * | ext-token "=" ext-value + * ext-token = + * @private + */ + +var DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/ // eslint-disable-line no-control-regex + +/** + * Create an attachment Content-Disposition header. + * + * @param {string} [filename] + * @param {object} [options] + * @param {string} [options.type=attachment] + * @param {string|boolean} [options.fallback=true] + * @return {string} + * @public + */ + +function contentDisposition (filename, options) { + var opts = options || {} + + // get type + var type = opts.type || 'attachment' + + // get parameters + var params = createparams(filename, opts.fallback) + + // format into string + return format(new ContentDisposition(type, params)) +} + +/** + * Create parameters object from filename and fallback. + * + * @param {string} [filename] + * @param {string|boolean} [fallback=true] + * @return {object} + * @private + */ + +function createparams (filename, fallback) { + if (filename === undefined) { + return + } + + var params = {} + + if (typeof filename !== 'string') { + throw new TypeError('filename must be a string') + } + + // fallback defaults to true + if (fallback === undefined) { + fallback = true + } + + if (typeof fallback !== 'string' && typeof fallback !== 'boolean') { + throw new TypeError('fallback must be a string or boolean') + } + + if (typeof fallback === 'string' && NON_LATIN1_REGEXP.test(fallback)) { + throw new TypeError('fallback must be ISO-8859-1 string') + } + + // restrict to file base name + var name = basename(filename) + + // determine if name is suitable for quoted string + var isQuotedString = TEXT_REGEXP.test(name) + + // generate fallback name + var fallbackName = typeof fallback !== 'string' + ? fallback && getlatin1(name) + : basename(fallback) + var hasFallback = typeof fallbackName === 'string' && fallbackName !== name + + // set extended filename parameter + if (hasFallback || !isQuotedString || hasHexEscape(name)) { + params['filename*'] = name + } + + // set filename parameter + if (isQuotedString || hasFallback) { + params.filename = hasFallback + ? fallbackName + : name + } + + return params +} + +/** + * Format object to Content-Disposition header. + * + * @param {object} obj + * @param {string} obj.type + * @param {object} [obj.parameters] + * @return {string} + * @private + */ + +function format (obj) { + var parameters = obj.parameters + var type = obj.type + + if (!type || typeof type !== 'string' || !TOKEN_REGEXP.test(type)) { + throw new TypeError('invalid type') + } + + // start with normalized type + var string = String(type).toLowerCase() + + // append parameters + if (parameters && typeof parameters === 'object') { + var param + var params = Object.keys(parameters).sort() + + for (var i = 0; i < params.length; i++) { + param = params[i] + + var val = param.slice(-1) === '*' + ? ustring(parameters[param]) + : qstring(parameters[param]) + + string += '; ' + param + '=' + val + } + } + + return string +} + +/** + * Decode a RFC 5987 field value (gracefully). + * + * @param {string} str + * @return {string} + * @private + */ + +function decodefield (str) { + const match = EXT_VALUE_REGEXP.exec(str) + + if (!match) { + throw new TypeError('invalid extended field value') + } + + const charset = match[1].toLowerCase() + const encoded = match[2] + + switch (charset) { + case 'iso-8859-1': + { + const binary = decodeHexEscapes(encoded) + return getlatin1(binary) + } + case 'utf-8': + case 'utf8': + { + try { + return decodeURIComponent(encoded) + } catch { + // Failed to decode with decodeURIComponent, fallback to lenient decoding which replaces invalid UTF-8 byte sequences with the Unicode replacement character + // TODO: Consider removing in the next major version to be more strict about invalid percent-encodings + const binary = decodeHexEscapes(encoded) + + const bytes = new Uint8Array(binary.length) + for (let idx = 0; idx < binary.length; idx++) { + bytes[idx] = binary.charCodeAt(idx) + } + + return utf8Decoder.decode(bytes) + } + } + } + throw new TypeError('unsupported charset in extended field') +} + +/** + * Get ISO-8859-1 version of string. + * + * @param {string} val + * @return {string} + * @private + */ + +function getlatin1 (val) { + // simple Unicode -> ISO-8859-1 transformation + return String(val).replace(NON_LATIN1_REGEXP, '?') +} + +/** + * Parse Content-Disposition header string. + * + * @param {string} string + * @return {object} + * @public + */ + +function parse (string) { + if (!string || typeof string !== 'string') { + throw new TypeError('argument string is required') + } + + var match = DISPOSITION_TYPE_REGEXP.exec(string) + + if (!match) { + throw new TypeError('invalid type format') + } + + // normalize type + var index = match[0].length + var type = match[1].toLowerCase() + + var key + var names = [] + var params = {} + var value + + // calculate index to start at + index = PARAM_REGEXP.lastIndex = match[0].slice(-1) === ';' + ? index - 1 + : index + + // match parameters + while ((match = PARAM_REGEXP.exec(string))) { + if (match.index !== index) { + throw new TypeError('invalid parameter format') + } + + index += match[0].length + key = match[1].toLowerCase() + value = match[2] + + if (names.indexOf(key) !== -1) { + throw new TypeError('invalid duplicate parameter') + } + + names.push(key) + + if (key.indexOf('*') + 1 === key.length) { + // decode extended value + key = key.slice(0, -1) + value = decodefield(value) + + // overwrite existing value + params[key] = value + continue + } + + if (typeof params[key] === 'string') { + continue + } + + if (value[0] === '"') { + // remove quotes and escapes + value = value + .slice(1, -1) + .replace(QESC_REGEXP, '$1') + } + + params[key] = value + } + + if (index !== -1 && index !== string.length) { + throw new TypeError('invalid parameter format') + } + + return new ContentDisposition(type, params) +} + +/** + * Percent encode a single character. + * + * @param {string} char + * @return {string} + * @private + */ + +function pencode (char) { + return '%' + String(char) + .charCodeAt(0) + .toString(16) + .toUpperCase() +} + +/** + * Quote a string for HTTP. + * + * @param {string} val + * @return {string} + * @private + */ + +function qstring (val) { + var str = String(val) + + return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' +} + +/** + * Encode a Unicode string for HTTP (RFC 5987). + * + * @param {string} val + * @return {string} + * @private + */ + +function ustring (val) { + var str = String(val) + + // percent encode as UTF-8 + var encoded = encodeURIComponent(str) + .replace(ENCODE_URL_ATTR_CHAR_REGEXP, pencode) + + return 'UTF-8\'\'' + encoded +} + +/** + * Class for parsed Content-Disposition header for v8 optimization + * + * @public + * @param {string} type + * @param {object} parameters + * @constructor + */ + +function ContentDisposition (type, parameters) { + this.type = type + this.parameters = parameters +} + +/** + * Return the last portion of a path + * + * @param {string} path + * @returns {string} + */ +function basename (path) { + const normalized = path.replaceAll('\\', '/') + + let end = normalized.length + while (end > 0 && normalized[end - 1] === '/') { + end-- + } + + if (end === 0) { + return '' + } + + let start = end - 1 + while (start >= 0 && normalized[start] !== '/') { + start-- + } + + return normalized.slice(start + 1, end) +} + +/** + * Check if a character is a hex digit [0-9A-Fa-f] + * + * @param {string} char + * @return {boolean} + * @private + */ +function isHexDigit (char) { + const code = char.charCodeAt(0) + return ( + (code >= 48 && code <= 57) || // 0-9 + (code >= 65 && code <= 70) || // A-F + (code >= 97 && code <= 102) // a-f + ) +} + +/** + * Check if a string contains percent encoding escapes. + * + * @param {string} str + * @return {boolean} + * @private + */ +function hasHexEscape (str) { + const maxIndex = str.length - 3 + let lastIndex = -1 + + while ((lastIndex = str.indexOf('%', lastIndex + 1)) !== -1 && lastIndex <= maxIndex) { + if (isHexDigit(str[lastIndex + 1]) && isHexDigit(str[lastIndex + 2])) { + return true + } + } + + return false +} + +/** + * Decode hex escapes in a string (e.g., %20 -> space) + * + * @param {string} str + * @return {string} + * @private + */ +function decodeHexEscapes (str) { + const firstEscape = str.indexOf('%') + if (firstEscape === -1) return str + + let result = str.slice(0, firstEscape) + for (let idx = firstEscape; idx < str.length; idx++) { + if ( + str[idx] === '%' && + idx + 2 < str.length && + isHexDigit(str[idx + 1]) && + isHexDigit(str[idx + 2]) + ) { + result += String.fromCharCode(Number.parseInt(str[idx + 1] + str[idx + 2], 16)) + idx += 2 + } else { + result += str[idx] + } + } + return result +} diff --git a/node_modules/content-disposition/package.json b/node_modules/content-disposition/package.json new file mode 100644 index 0000000..ed3f619 --- /dev/null +++ b/node_modules/content-disposition/package.json @@ -0,0 +1,40 @@ +{ + "name": "content-disposition", + "description": "Create and parse Content-Disposition header", + "version": "1.1.0", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "keywords": [ + "content-disposition", + "http", + "rfc6266", + "res" + ], + "repository": "jshttp/content-disposition", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + }, + "devDependencies": { + "c8": "^10.1.2", + "eslint": "^8.57.1", + "eslint-config-standard": "^14.1.1", + "eslint-plugin-import": "^2.32.0", + "eslint-plugin-markdown": "^3.0.1", + "eslint-plugin-node": "^11.1.0", + "eslint-plugin-promise": "^6.6.0", + "eslint-plugin-standard": "^4.1.0" + }, + "files": [ + "index.js" + ], + "engines": { + "node": ">=18" + }, + "scripts": { + "lint": "eslint .", + "test": "node --test --test-reporter spec", + "test-ci": "c8 --reporter=lcovonly --reporter=text npm test", + "test-cov": "c8 --reporter=html --reporter=text npm test" + } +} diff --git a/node_modules/content-type/HISTORY.md b/node_modules/content-type/HISTORY.md new file mode 100644 index 0000000..4583671 --- /dev/null +++ b/node_modules/content-type/HISTORY.md @@ -0,0 +1,29 @@ +1.0.5 / 2023-01-29 +================== + + * perf: skip value escaping when unnecessary + +1.0.4 / 2017-09-11 +================== + + * perf: skip parameter parsing when no parameters + +1.0.3 / 2017-09-10 +================== + + * perf: remove argument reassignment + +1.0.2 / 2016-05-09 +================== + + * perf: enable strict mode + +1.0.1 / 2015-02-13 +================== + + * Improve missing `Content-Type` header error message + +1.0.0 / 2015-02-01 +================== + + * Initial implementation, derived from `media-typer@0.3.0` diff --git a/node_modules/content-type/LICENSE b/node_modules/content-type/LICENSE new file mode 100644 index 0000000..34b1a2d --- /dev/null +++ b/node_modules/content-type/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2015 Douglas Christopher Wilson + +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. diff --git a/node_modules/content-type/README.md b/node_modules/content-type/README.md new file mode 100644 index 0000000..c1a922a --- /dev/null +++ b/node_modules/content-type/README.md @@ -0,0 +1,94 @@ +# content-type + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][ci-image]][ci-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +Create and parse HTTP Content-Type header according to RFC 7231 + +## Installation + +```sh +$ npm install content-type +``` + +## API + +```js +var contentType = require('content-type') +``` + +### contentType.parse(string) + +```js +var obj = contentType.parse('image/svg+xml; charset=utf-8') +``` + +Parse a `Content-Type` header. This will return an object with the following +properties (examples are shown for the string `'image/svg+xml; charset=utf-8'`): + + - `type`: The media type (the type and subtype, always lower case). + Example: `'image/svg+xml'` + + - `parameters`: An object of the parameters in the media type (name of parameter + always lower case). Example: `{charset: 'utf-8'}` + +Throws a `TypeError` if the string is missing or invalid. + +### contentType.parse(req) + +```js +var obj = contentType.parse(req) +``` + +Parse the `Content-Type` header from the given `req`. Short-cut for +`contentType.parse(req.headers['content-type'])`. + +Throws a `TypeError` if the `Content-Type` header is missing or invalid. + +### contentType.parse(res) + +```js +var obj = contentType.parse(res) +``` + +Parse the `Content-Type` header set on the given `res`. Short-cut for +`contentType.parse(res.getHeader('content-type'))`. + +Throws a `TypeError` if the `Content-Type` header is missing or invalid. + +### contentType.format(obj) + +```js +var str = contentType.format({ + type: 'image/svg+xml', + parameters: { charset: 'utf-8' } +}) +``` + +Format an object into a `Content-Type` header. This will return a string of the +content type for the given object with the following properties (examples are +shown that produce the string `'image/svg+xml; charset=utf-8'`): + + - `type`: The media type (will be lower-cased). Example: `'image/svg+xml'` + + - `parameters`: An object of the parameters in the media type (name of the + parameter will be lower-cased). Example: `{charset: 'utf-8'}` + +Throws a `TypeError` if the object contains an invalid type or parameter names. + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/content-type/master?label=ci +[ci-url]: https://github.com/jshttp/content-type/actions/workflows/ci.yml +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/content-type/master +[coveralls-url]: https://coveralls.io/r/jshttp/content-type?branch=master +[node-image]: https://badgen.net/npm/node/content-type +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/content-type +[npm-url]: https://npmjs.org/package/content-type +[npm-version-image]: https://badgen.net/npm/v/content-type diff --git a/node_modules/content-type/index.js b/node_modules/content-type/index.js new file mode 100644 index 0000000..41840e7 --- /dev/null +++ b/node_modules/content-type/index.js @@ -0,0 +1,225 @@ +/*! + * content-type + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 + * + * parameter = token "=" ( token / quoted-string ) + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + * / DIGIT / ALPHA + * ; any VCHAR, except delimiters + * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE + * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text + * obs-text = %x80-FF + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + */ +var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g // eslint-disable-line no-control-regex +var TEXT_REGEXP = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/ // eslint-disable-line no-control-regex +var TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ + +/** + * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 + * + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + * obs-text = %x80-FF + */ +var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g // eslint-disable-line no-control-regex + +/** + * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6 + */ +var QUOTE_REGEXP = /([\\"])/g + +/** + * RegExp to match type in RFC 7231 sec 3.1.1.1 + * + * media-type = type "/" subtype + * type = token + * subtype = token + */ +var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ + +/** + * Module exports. + * @public + */ + +exports.format = format +exports.parse = parse + +/** + * Format object to media type. + * + * @param {object} obj + * @return {string} + * @public + */ + +function format (obj) { + if (!obj || typeof obj !== 'object') { + throw new TypeError('argument obj is required') + } + + var parameters = obj.parameters + var type = obj.type + + if (!type || !TYPE_REGEXP.test(type)) { + throw new TypeError('invalid type') + } + + var string = type + + // append parameters + if (parameters && typeof parameters === 'object') { + var param + var params = Object.keys(parameters).sort() + + for (var i = 0; i < params.length; i++) { + param = params[i] + + if (!TOKEN_REGEXP.test(param)) { + throw new TypeError('invalid parameter name') + } + + string += '; ' + param + '=' + qstring(parameters[param]) + } + } + + return string +} + +/** + * Parse media type to object. + * + * @param {string|object} string + * @return {Object} + * @public + */ + +function parse (string) { + if (!string) { + throw new TypeError('argument string is required') + } + + // support req/res-like objects as argument + var header = typeof string === 'object' + ? getcontenttype(string) + : string + + if (typeof header !== 'string') { + throw new TypeError('argument string is required to be a string') + } + + var index = header.indexOf(';') + var type = index !== -1 + ? header.slice(0, index).trim() + : header.trim() + + if (!TYPE_REGEXP.test(type)) { + throw new TypeError('invalid media type') + } + + var obj = new ContentType(type.toLowerCase()) + + // parse parameters + if (index !== -1) { + var key + var match + var value + + PARAM_REGEXP.lastIndex = index + + while ((match = PARAM_REGEXP.exec(header))) { + if (match.index !== index) { + throw new TypeError('invalid parameter format') + } + + index += match[0].length + key = match[1].toLowerCase() + value = match[2] + + if (value.charCodeAt(0) === 0x22 /* " */) { + // remove quotes + value = value.slice(1, -1) + + // remove escapes + if (value.indexOf('\\') !== -1) { + value = value.replace(QESC_REGEXP, '$1') + } + } + + obj.parameters[key] = value + } + + if (index !== header.length) { + throw new TypeError('invalid parameter format') + } + } + + return obj +} + +/** + * Get content-type from req/res objects. + * + * @param {object} + * @return {Object} + * @private + */ + +function getcontenttype (obj) { + var header + + if (typeof obj.getHeader === 'function') { + // res-like + header = obj.getHeader('content-type') + } else if (typeof obj.headers === 'object') { + // req-like + header = obj.headers && obj.headers['content-type'] + } + + if (typeof header !== 'string') { + throw new TypeError('content-type header is missing from object') + } + + return header +} + +/** + * Quote a string if necessary. + * + * @param {string} val + * @return {string} + * @private + */ + +function qstring (val) { + var str = String(val) + + // no need to quote tokens + if (TOKEN_REGEXP.test(str)) { + return str + } + + if (str.length > 0 && !TEXT_REGEXP.test(str)) { + throw new TypeError('invalid parameter value') + } + + return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' +} + +/** + * Class to represent a content type. + * @private + */ +function ContentType (type) { + this.parameters = Object.create(null) + this.type = type +} diff --git a/node_modules/content-type/package.json b/node_modules/content-type/package.json new file mode 100644 index 0000000..9db19f6 --- /dev/null +++ b/node_modules/content-type/package.json @@ -0,0 +1,42 @@ +{ + "name": "content-type", + "description": "Create and parse HTTP Content-Type header", + "version": "1.0.5", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "keywords": [ + "content-type", + "http", + "req", + "res", + "rfc7231" + ], + "repository": "jshttp/content-type", + "devDependencies": { + "deep-equal": "1.0.1", + "eslint": "8.32.0", + "eslint-config-standard": "15.0.1", + "eslint-plugin-import": "2.27.5", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "6.1.1", + "eslint-plugin-standard": "4.1.0", + "mocha": "10.2.0", + "nyc": "15.1.0" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-ci": "nyc --reporter=lcovonly --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/node_modules/cookie-signature/History.md b/node_modules/cookie-signature/History.md new file mode 100644 index 0000000..479211a --- /dev/null +++ b/node_modules/cookie-signature/History.md @@ -0,0 +1,70 @@ +1.2.2 / 2024-10-29 +================== + +* various metadata/documentation tweaks (incl. #51) + + +1.2.1 / 2023-02-27 +================== + +* update annotations for allowed secret key types (#44, thanks @jyasskin!) + + +1.2.0 / 2022-02-17 +================== + +* allow buffer and other node-supported types as key (#33) +* be pickier about extra content after signed portion (#40) +* some internal code clarity/cleanup improvements (#26) + + +1.1.0 / 2018-01-18 +================== + +* switch to built-in `crypto.timingSafeEqual` for validation instead of previous double-hash method (thank you @jodevsa!) + + +1.0.7 / 2023-04-12 +================== + +Later release for older node.js versions. See the [v1.0.x branch notes](https://github.com/tj/node-cookie-signature/blob/v1.0.x/History.md#107--2023-04-12). + + +1.0.6 / 2015-02-03 +================== + +* use `npm test` instead of `make test` to run tests +* clearer assertion messages when checking input + + +1.0.5 / 2014-09-05 +================== + +* add license to package.json + +1.0.4 / 2014-06-25 +================== + + * corrected avoidance of timing attacks (thanks @tenbits!) + +1.0.3 / 2014-01-28 +================== + + * [incorrect] fix for timing attacks + +1.0.2 / 2014-01-28 +================== + + * fix missing repository warning + * fix typo in test + +1.0.1 / 2013-04-15 +================== + + * Revert "Changed underlying HMAC algo. to sha512." + * Revert "Fix for timing attacks on MAC verification." + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/cookie-signature/LICENSE b/node_modules/cookie-signature/LICENSE new file mode 100644 index 0000000..a2671bf --- /dev/null +++ b/node_modules/cookie-signature/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2012–2024 LearnBoost and other 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. diff --git a/node_modules/cookie-signature/Readme.md b/node_modules/cookie-signature/Readme.md new file mode 100644 index 0000000..369af15 --- /dev/null +++ b/node_modules/cookie-signature/Readme.md @@ -0,0 +1,23 @@ + +# cookie-signature + + Sign and unsign cookies. + +## Example + +```js +var cookie = require('cookie-signature'); + +var val = cookie.sign('hello', 'tobiiscool'); +val.should.equal('hello.DGDUkGlIkCzPz+C0B064FNgHdEjox7ch8tOBGslZ5QI'); + +var val = cookie.sign('hello', 'tobiiscool'); +cookie.unsign(val, 'tobiiscool').should.equal('hello'); +cookie.unsign(val, 'luna').should.be.false; +``` + +## License + +MIT. + +See LICENSE file for details. diff --git a/node_modules/cookie-signature/index.js b/node_modules/cookie-signature/index.js new file mode 100644 index 0000000..3fbbddb --- /dev/null +++ b/node_modules/cookie-signature/index.js @@ -0,0 +1,47 @@ +/** + * Module dependencies. + */ + +var crypto = require('crypto'); + +/** + * Sign the given `val` with `secret`. + * + * @param {String} val + * @param {String|NodeJS.ArrayBufferView|crypto.KeyObject} secret + * @return {String} + * @api private + */ + +exports.sign = function(val, secret){ + if ('string' != typeof val) throw new TypeError("Cookie value must be provided as a string."); + if (null == secret) throw new TypeError("Secret key must be provided."); + return val + '.' + crypto + .createHmac('sha256', secret) + .update(val) + .digest('base64') + .replace(/\=+$/, ''); +}; + +/** + * Unsign and decode the given `input` with `secret`, + * returning `false` if the signature is invalid. + * + * @param {String} input + * @param {String|NodeJS.ArrayBufferView|crypto.KeyObject} secret + * @return {String|Boolean} + * @api private + */ + +exports.unsign = function(input, secret){ + if ('string' != typeof input) throw new TypeError("Signed cookie string must be provided."); + if (null == secret) throw new TypeError("Secret key must be provided."); + var tentativeValue = input.slice(0, input.lastIndexOf('.')), + expectedInput = exports.sign(tentativeValue, secret), + expectedBuffer = Buffer.from(expectedInput), + inputBuffer = Buffer.from(input); + return ( + expectedBuffer.length === inputBuffer.length && + crypto.timingSafeEqual(expectedBuffer, inputBuffer) + ) ? tentativeValue : false; +}; diff --git a/node_modules/cookie-signature/package.json b/node_modules/cookie-signature/package.json new file mode 100644 index 0000000..a160040 --- /dev/null +++ b/node_modules/cookie-signature/package.json @@ -0,0 +1,24 @@ +{ + "name": "cookie-signature", + "version": "1.2.2", + "main": "index.js", + "description": "Sign and unsign cookies", + "keywords": ["cookie", "sign", "unsign"], + "author": "TJ Holowaychuk ", + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/visionmedia/node-cookie-signature.git" + }, + "dependencies": {}, + "engines": { + "node": ">=6.6.0" + }, + "devDependencies": { + "mocha": "*", + "should": "*" + }, + "scripts": { + "test": "mocha --require should --reporter spec" + } +} diff --git a/node_modules/cookie/LICENSE b/node_modules/cookie/LICENSE new file mode 100644 index 0000000..058b6b4 --- /dev/null +++ b/node_modules/cookie/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2012-2014 Roman Shtylman +Copyright (c) 2015 Douglas Christopher Wilson + +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. + diff --git a/node_modules/cookie/README.md b/node_modules/cookie/README.md new file mode 100644 index 0000000..71fdac1 --- /dev/null +++ b/node_modules/cookie/README.md @@ -0,0 +1,317 @@ +# cookie + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][ci-image]][ci-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +Basic HTTP cookie parser and serializer for HTTP servers. + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install cookie +``` + +## API + +```js +var cookie = require('cookie'); +``` + +### cookie.parse(str, options) + +Parse an HTTP `Cookie` header string and returning an object of all cookie name-value pairs. +The `str` argument is the string representing a `Cookie` header value and `options` is an +optional object containing additional parsing options. + +```js +var cookies = cookie.parse('foo=bar; equation=E%3Dmc%5E2'); +// { foo: 'bar', equation: 'E=mc^2' } +``` + +#### Options + +`cookie.parse` accepts these properties in the options object. + +##### decode + +Specifies a function that will be used to decode a cookie's value. Since the value of a cookie +has a limited character set (and must be a simple string), this function can be used to decode +a previously-encoded cookie value into a JavaScript string or other object. + +The default function is the global `decodeURIComponent`, which will decode any URL-encoded +sequences into their byte representations. + +**note** if an error is thrown from this function, the original, non-decoded cookie value will +be returned as the cookie's value. + +### cookie.serialize(name, value, options) + +Serialize a cookie name-value pair into a `Set-Cookie` header string. The `name` argument is the +name for the cookie, the `value` argument is the value to set the cookie to, and the `options` +argument is an optional object containing additional serialization options. + +```js +var setCookie = cookie.serialize('foo', 'bar'); +// foo=bar +``` + +#### Options + +`cookie.serialize` accepts these properties in the options object. + +##### domain + +Specifies the value for the [`Domain` `Set-Cookie` attribute][rfc-6265-5.2.3]. By default, no +domain is set, and most clients will consider the cookie to apply to only the current domain. + +##### encode + +Specifies a function that will be used to encode a cookie's value. Since value of a cookie +has a limited character set (and must be a simple string), this function can be used to encode +a value into a string suited for a cookie's value. + +The default function is the global `encodeURIComponent`, which will encode a JavaScript string +into UTF-8 byte sequences and then URL-encode any that fall outside of the cookie range. + +##### expires + +Specifies the `Date` object to be the value for the [`Expires` `Set-Cookie` attribute][rfc-6265-5.2.1]. +By default, no expiration is set, and most clients will consider this a "non-persistent cookie" and +will delete it on a condition like exiting a web browser application. + +**note** the [cookie storage model specification][rfc-6265-5.3] states that if both `expires` and +`maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this, +so if both are set, they should point to the same date and time. + +##### httpOnly + +Specifies the `boolean` value for the [`HttpOnly` `Set-Cookie` attribute][rfc-6265-5.2.6]. When truthy, +the `HttpOnly` attribute is set, otherwise it is not. By default, the `HttpOnly` attribute is not set. + +**note** be careful when setting this to `true`, as compliant clients will not allow client-side +JavaScript to see the cookie in `document.cookie`. + +##### maxAge + +Specifies the `number` (in seconds) to be the value for the [`Max-Age` `Set-Cookie` attribute][rfc-6265-5.2.2]. +The given number will be converted to an integer by rounding down. By default, no maximum age is set. + +**note** the [cookie storage model specification][rfc-6265-5.3] states that if both `expires` and +`maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this, +so if both are set, they should point to the same date and time. + +##### partitioned + +Specifies the `boolean` value for the [`Partitioned` `Set-Cookie`](rfc-cutler-httpbis-partitioned-cookies) +attribute. When truthy, the `Partitioned` attribute is set, otherwise it is not. By default, the +`Partitioned` attribute is not set. + +**note** This is an attribute that has not yet been fully standardized, and may change in the future. +This also means many clients may ignore this attribute until they understand it. + +More information about can be found in [the proposal](https://github.com/privacycg/CHIPS). + +##### path + +Specifies the value for the [`Path` `Set-Cookie` attribute][rfc-6265-5.2.4]. By default, the path +is considered the ["default path"][rfc-6265-5.1.4]. + +##### priority + +Specifies the `string` to be the value for the [`Priority` `Set-Cookie` attribute][rfc-west-cookie-priority-00-4.1]. + + - `'low'` will set the `Priority` attribute to `Low`. + - `'medium'` will set the `Priority` attribute to `Medium`, the default priority when not set. + - `'high'` will set the `Priority` attribute to `High`. + +More information about the different priority levels can be found in +[the specification][rfc-west-cookie-priority-00-4.1]. + +**note** This is an attribute that has not yet been fully standardized, and may change in the future. +This also means many clients may ignore this attribute until they understand it. + +##### sameSite + +Specifies the `boolean` or `string` to be the value for the [`SameSite` `Set-Cookie` attribute][rfc-6265bis-09-5.4.7]. + + - `true` will set the `SameSite` attribute to `Strict` for strict same site enforcement. + - `false` will not set the `SameSite` attribute. + - `'lax'` will set the `SameSite` attribute to `Lax` for lax same site enforcement. + - `'none'` will set the `SameSite` attribute to `None` for an explicit cross-site cookie. + - `'strict'` will set the `SameSite` attribute to `Strict` for strict same site enforcement. + +More information about the different enforcement levels can be found in +[the specification][rfc-6265bis-09-5.4.7]. + +**note** This is an attribute that has not yet been fully standardized, and may change in the future. +This also means many clients may ignore this attribute until they understand it. + +##### secure + +Specifies the `boolean` value for the [`Secure` `Set-Cookie` attribute][rfc-6265-5.2.5]. When truthy, +the `Secure` attribute is set, otherwise it is not. By default, the `Secure` attribute is not set. + +**note** be careful when setting this to `true`, as compliant clients will not send the cookie back to +the server in the future if the browser does not have an HTTPS connection. + +## Example + +The following example uses this module in conjunction with the Node.js core HTTP server +to prompt a user for their name and display it back on future visits. + +```js +var cookie = require('cookie'); +var escapeHtml = require('escape-html'); +var http = require('http'); +var url = require('url'); + +function onRequest(req, res) { + // Parse the query string + var query = url.parse(req.url, true, true).query; + + if (query && query.name) { + // Set a new cookie with the name + res.setHeader('Set-Cookie', cookie.serialize('name', String(query.name), { + httpOnly: true, + maxAge: 60 * 60 * 24 * 7 // 1 week + })); + + // Redirect back after setting cookie + res.statusCode = 302; + res.setHeader('Location', req.headers.referer || '/'); + res.end(); + return; + } + + // Parse the cookies on the request + var cookies = cookie.parse(req.headers.cookie || ''); + + // Get the visitor name set in the cookie + var name = cookies.name; + + res.setHeader('Content-Type', 'text/html; charset=UTF-8'); + + if (name) { + res.write('

Welcome back, ' + escapeHtml(name) + '!

'); + } else { + res.write('

Hello, new visitor!

'); + } + + res.write('
'); + res.write(' '); + res.end('
'); +} + +http.createServer(onRequest).listen(3000); +``` + +## Testing + +```sh +$ npm test +``` + +## Benchmark + +``` +$ npm run bench + +> cookie@0.5.0 bench +> node benchmark/index.js + + node@18.18.2 + acorn@8.10.0 + ada@2.6.0 + ares@1.19.1 + brotli@1.0.9 + cldr@43.1 + icu@73.2 + llhttp@6.0.11 + modules@108 + napi@9 + nghttp2@1.57.0 + nghttp3@0.7.0 + ngtcp2@0.8.1 + openssl@3.0.10+quic + simdutf@3.2.14 + tz@2023c + undici@5.26.3 + unicode@15.0 + uv@1.44.2 + uvwasi@0.0.18 + v8@10.2.154.26-node.26 + zlib@1.2.13.1-motley + +> node benchmark/parse-top.js + + cookie.parse - top sites + + 14 tests completed. + + parse accounts.google.com x 2,588,913 ops/sec ±0.74% (186 runs sampled) + parse apple.com x 2,370,002 ops/sec ±0.69% (186 runs sampled) + parse cloudflare.com x 2,213,102 ops/sec ±0.88% (188 runs sampled) + parse docs.google.com x 2,194,157 ops/sec ±1.03% (184 runs sampled) + parse drive.google.com x 2,265,084 ops/sec ±0.79% (187 runs sampled) + parse en.wikipedia.org x 457,099 ops/sec ±0.81% (186 runs sampled) + parse linkedin.com x 504,407 ops/sec ±0.89% (186 runs sampled) + parse maps.google.com x 1,230,959 ops/sec ±0.98% (186 runs sampled) + parse microsoft.com x 926,294 ops/sec ±0.88% (184 runs sampled) + parse play.google.com x 2,311,338 ops/sec ±0.83% (185 runs sampled) + parse support.google.com x 1,508,850 ops/sec ±0.86% (186 runs sampled) + parse www.google.com x 1,022,582 ops/sec ±1.32% (182 runs sampled) + parse youtu.be x 332,136 ops/sec ±1.02% (185 runs sampled) + parse youtube.com x 323,833 ops/sec ±0.77% (183 runs sampled) + +> node benchmark/parse.js + + cookie.parse - generic + + 6 tests completed. + + simple x 3,214,032 ops/sec ±1.61% (183 runs sampled) + decode x 587,237 ops/sec ±1.16% (187 runs sampled) + unquote x 2,954,618 ops/sec ±1.35% (183 runs sampled) + duplicates x 857,008 ops/sec ±0.89% (187 runs sampled) + 10 cookies x 292,133 ops/sec ±0.89% (187 runs sampled) + 100 cookies x 22,610 ops/sec ±0.68% (187 runs sampled) +``` + +## References + +- [RFC 6265: HTTP State Management Mechanism][rfc-6265] +- [Same-site Cookies][rfc-6265bis-09-5.4.7] + +[rfc-cutler-httpbis-partitioned-cookies]: https://tools.ietf.org/html/draft-cutler-httpbis-partitioned-cookies/ +[rfc-west-cookie-priority-00-4.1]: https://tools.ietf.org/html/draft-west-cookie-priority-00#section-4.1 +[rfc-6265bis-09-5.4.7]: https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-09#section-5.4.7 +[rfc-6265]: https://tools.ietf.org/html/rfc6265 +[rfc-6265-5.1.4]: https://tools.ietf.org/html/rfc6265#section-5.1.4 +[rfc-6265-5.2.1]: https://tools.ietf.org/html/rfc6265#section-5.2.1 +[rfc-6265-5.2.2]: https://tools.ietf.org/html/rfc6265#section-5.2.2 +[rfc-6265-5.2.3]: https://tools.ietf.org/html/rfc6265#section-5.2.3 +[rfc-6265-5.2.4]: https://tools.ietf.org/html/rfc6265#section-5.2.4 +[rfc-6265-5.2.5]: https://tools.ietf.org/html/rfc6265#section-5.2.5 +[rfc-6265-5.2.6]: https://tools.ietf.org/html/rfc6265#section-5.2.6 +[rfc-6265-5.3]: https://tools.ietf.org/html/rfc6265#section-5.3 + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/cookie/master?label=ci +[ci-url]: https://github.com/jshttp/cookie/actions/workflows/ci.yml +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/cookie/master +[coveralls-url]: https://coveralls.io/r/jshttp/cookie?branch=master +[node-image]: https://badgen.net/npm/node/cookie +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/cookie +[npm-url]: https://npmjs.org/package/cookie +[npm-version-image]: https://badgen.net/npm/v/cookie diff --git a/node_modules/cookie/SECURITY.md b/node_modules/cookie/SECURITY.md new file mode 100644 index 0000000..fd4a6c5 --- /dev/null +++ b/node_modules/cookie/SECURITY.md @@ -0,0 +1,25 @@ +# Security Policies and Procedures + +## Reporting a Bug + +The `cookie` team and community take all security bugs seriously. Thank +you for improving the security of the project. We appreciate your efforts and +responsible disclosure and will make every effort to acknowledge your +contributions. + +Report security bugs by emailing the current owner(s) of `cookie`. This +information can be found in the npm registry using the command +`npm owner ls cookie`. +If unsure or unable to get the information from the above, open an issue +in the [project issue tracker](https://github.com/jshttp/cookie/issues) +asking for the current contact information. + +To ensure the timely response to your report, please ensure that the entirety +of the report is contained within the email body and not solely behind a web +link or an attachment. + +At least one owner will acknowledge your email within 48 hours, and will send a +more detailed response within 48 hours indicating the next steps in handling +your report. After the initial reply to your report, the owners will +endeavor to keep you informed of the progress towards a fix and full +announcement, and may ask for additional information or guidance. diff --git a/node_modules/cookie/index.js b/node_modules/cookie/index.js new file mode 100644 index 0000000..acd5acd --- /dev/null +++ b/node_modules/cookie/index.js @@ -0,0 +1,335 @@ +/*! + * cookie + * Copyright(c) 2012-2014 Roman Shtylman + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +exports.parse = parse; +exports.serialize = serialize; + +/** + * Module variables. + * @private + */ + +var __toString = Object.prototype.toString +var __hasOwnProperty = Object.prototype.hasOwnProperty + +/** + * RegExp to match cookie-name in RFC 6265 sec 4.1.1 + * This refers out to the obsoleted definition of token in RFC 2616 sec 2.2 + * which has been replaced by the token definition in RFC 7230 appendix B. + * + * cookie-name = token + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / + * "*" / "+" / "-" / "." / "^" / "_" / + * "`" / "|" / "~" / DIGIT / ALPHA + */ + +var cookieNameRegExp = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; + +/** + * RegExp to match cookie-value in RFC 6265 sec 4.1.1 + * + * cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE ) + * cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E + * ; US-ASCII characters excluding CTLs, + * ; whitespace DQUOTE, comma, semicolon, + * ; and backslash + */ + +var cookieValueRegExp = /^("?)[\u0021\u0023-\u002B\u002D-\u003A\u003C-\u005B\u005D-\u007E]*\1$/; + +/** + * RegExp to match domain-value in RFC 6265 sec 4.1.1 + * + * domain-value = + * ; defined in [RFC1034], Section 3.5, as + * ; enhanced by [RFC1123], Section 2.1 + * =